1、常用API。
方法 | 概述 |
---|
now() | 根据当前时间创建对象 |
of() | 根据指定时间创建对象 |
plusDays()/ plusWeeks()/plusMonths()/plusYears() | 向当前 LocalDate 对象添加几天、几周、几月、几年 |
minusDays()/minusWeeks()/minusMonths()/minusYears() | 从当前 LocalDate 对象减去几天、几周、几月、几年 |
plus, minus | 添加或减少一个 Duration 或 Period |
withDayOfMonth()/withDayOfYear()/withMonth()/withYear() | 将月份天数、年份天数、月份、年份 修 改 为 指 定 的 值 并 返 回 新 的LocalDate 对象 |
getDayOfMonth()/getDayOfYear()/getDayOfWeek() | 获得月份天数(1-31),获得年份天数(1-366),获得星期几(返回一个 DayOfWeek枚举值) |
getMonth()/getMonthValue()/getYear() | 获得月份, 返回一个 Month 枚举值,获得月份(1-12),年份 |
until() | 获得两个日期之间的 Period 对象,或者指定 ChronoUnits 的数字 |
isBefore()/ isAfter() | 比较两个 LocalDate |
isLeapYear() | 判断是否是闰年 |
2、获取日期或时间。
@Test
public void test1() {
System.out.println(LocalDate.now());
System.out.println(LocalTime.now());
System.out.println(LocalDateTime.now());
System.out.println(LocalDate.of(2015, 10, 15));
System.out.println(LocalTime.of(9,58));
}
3、Instant 时间戳。
- 用于“时间戳”的运算。它是以Unix元年(传统的设定为UTC时区1970年1月1日午夜时分)开始所经历的描述进行运算。
@Test
public void test2() {
Instant ins1 = Instant.now();
OffsetDateTime ofd = ins1.atOffset(ZoneOffset.ofHours(8));
System.out.println(ins1.toEpochMilli());
Instant ins2 = Instant.ofEpochSecond(600);
System.out.println(ins2);
}
4、Duration 和 Period。
@Test
public void test3() {
Instant ins1 = Instant.now();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Instant ins2 = Instant.now();
Duration dur = Duration.between(ins1, ins2);
System.out.println(dur.toMillis());
LocalDateTime ls1 = LocalDateTime.now();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalDateTime ls2 = LocalDateTime.now();
Duration dus = Duration.between(ls1, ls2);
System.out.println(dus.toMillis());
}
@Test
public void test4() {
LocalDate ls1 = LocalDate.of(2013, 10, 21);
LocalDate ls2 = LocalDate.now();
Period per = Period.between(ls1, ls2);
System.out.println(per.getYears() + "年" + per.getMonths() + "月" + per.getDays()+"天");
}
5、TemporalAdjuster : 时间校正器。
- TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。
@Test
public void test5() {
LocalDateTime ls1 = LocalDateTime.now();
System.out.println(ls1);
LocalDateTime ls2 = ls1.withDayOfMonth(10);
System.out.println(ls2);
LocalDateTime ls3 = ls1.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(ls3);
}
6、DateTimeFormatter:解析与格式化。
@Test
public void test6() {
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime ld1 = LocalDateTime.now();
System.out.println(ld1.format(dtf));
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(dtf2.format(ld1));
}
7、时区
@Test
public void test7() {
Set<String> set = ZoneId.getAvailableZoneIds();
set.forEach(System.out::println);
}
@Test
public void test9() {
System.out.println(ZonedDateTime.now());
}
- of(id) : 用指定的时区信息获取 ZoneId 对象。
@Test
public void test8() {
LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Zagreb"));
System.out.println(ldt);
}