- 表示当前系统的此刻日期时间
构造器
| 名称 | 说明 |
|---|---|
| public Date() | 创建一个Date对象,代表系统此刻日期时间 |
| public Date(long time) | 把时间毫秒值转换成Date日期对象 |
Date常用方法
| 名称 | 说明 |
|---|---|
| public long getTime() | 获取时间对象的毫秒值(从1970年1月1日至今) |
| public void setTime(long time) | 设置日期对象的时间为当前time对应的时间 |
| before(Date d) | 当前date是否在d之前 |
| after(Date d) | 当前date是否在d之后 |
- 将Date对象或时间毫秒值格式化为我们喜欢的时间形式
- 也可以将字符串的时间形式解析成日期对象
构造器
| 构造器 | 说明 |
|---|---|
| public SimpleDateFormat() | 默认格式 |
| public SimpleDateFormat(String pattern) | 指定格式 |
pattern: yyyy年MM月dd日 HH:mm:ss EEE a
E:星期几 a:上下午
格式化方法
| 格式化方法 | 说明 |
|---|---|
| public final String format(Date date) | 将日期格式化为日期/时间字符串 |
| public final String format(Object time) | 将时间毫秒值格式化成日期/时间字符串 |
解析字符串
| 解析方法 | 说明 |
|---|---|
| public Date parse(String source) | 从给定字符串的开始解析文本生成时间 |
- 代表系统此刻日期的日历对象
- 抽象类,不能直接创建对象
| 方法名 | 说明 |
|---|---|
| public static Calendar getInstance() | 获取当前日历对象 |
| public int get(int field) | 取日期中的某个字段信息 |
| public void set(int field, int value) | 修改日历中的某个字段信息 |
| public void add(int field, int amount) | 为某个字段增加/减少指定的值 |
| public final Date getTime() | 拿到此刻日期对象 |
| public long getTimeInMillis() | 拿到此刻时间毫秒值 |
- 分别表示日期、时间和日期时间对象,他们的类的实例是不可变对象
- 三者构造对象和API是通用的
构建对象
| 方法名 | 说明 |
|---|---|
| public static Xxxx now() | 静态方法,根据当前时间创建对象 |
| public static Xxxx of(…) | 静态方法,指定日期/时间创建对象 |
LocalDateTime的转换API
| 方法名 | 说明 |
|---|---|
| public LocalDate toLocalDate() | 转换成一个LocalDate对象 |
| public LocalTime toLocalTime() | 转换成一个LocalTime对象 |
修改相关的API
| 方法名 | 说明 |
|---|---|
| plusDays | 向当前LocalDate对象添加几天 |
| minusDays | 从当前LocalDate对象减去几天 |
| withDayOfMonth | 将月份天数修改为指定的值并返回新的LocalDate对象 |
| isBefore, isAfter | 比较两个LocalDate |
Instant instant = Instant.now(); Date date = Date.from(instant); instant = date.toInstant();6.DateTimeFormatter
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String ldtStr = dtf.format(ldt);
7.Duration/Period
Period
- 计算日期间隔,用于LocalDate的比较
LocalDate today = LocalDate.now(); LocalDate birthDate = LocalDate.of(2002, 6, 5); Period period = Period.between(birthDate, today); //第二个参数减第一个参数 period.getYears() period.getMonths() period.getDays()
Duration
- 计算时间间隔,用于LocalDateTime和Instant
LocalDateTime today = LocalDateTime.now(); LocalDateTime birthDate = LocalDateTime.of(1990, 10, 1, 10, 50, 30); Duration duration = Duration.between(birthDate, today); duration.toDays() duration.toHours() duration.toMinutes() duration.toMillis() duration.toNanos()8.ChronoUnit
- 最全的,计算时间间隔
- between()



