jdk8 时间
//一个时间表示String stringDate = "2020-01-02 22:00:00";//初始化三个时区ZoneId chinaTimeZone = ZoneId.of("Asia/Shanghai");ZoneId americaTimeZone = ZoneId.of("America/New_York");ZoneOffset customTimeZone = ZoneOffset.ofHours(9);// 字面量+时区 转 时间// 1.方式一DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss");ZonedDateTime zonedDateTime = ZonedDateTime.of(LocalDateTime.parse(stringDate, formatter),chinaTimeZone);// 2020-01-02T22:00+08:00[Asia/Shanghai]System.out.println(zonedDateTime);// 2.方式二DateTimeFormatter formatterWithTimeZone = DateTimeFormatter.ofPattern("yyy-MM-dd HH:mm:ss").withZone(customTimeZone);ZonedDateTime z = ZonedDateTime.parse(stringDate,formatterWithTimeZone);// 2020-01-02T22:00+09:00System.out.println(z);// 时间转字面量String stringTime = z.format(formatterWithTimeZone.withZone(americaTimeZone));// 2020-01-02 08:00:00System.out.println(stringTime);
// 格式化字面量 formatter 的另一种方式DateTimeFormatter matter = new DateTimeFormatterBuilder().appendValue(ChronoField.YEAR) //年.appendLiteral("/").appendValue(ChronoField.MONTH_OF_YEAR) //月.appendLiteral("/").appendValue(ChronoField.DAY_OF_MONTH) //日.appendLiteral(" ").appendValue(ChronoField.HOUR_OF_DAY) //时.appendLiteral(":").appendValue(ChronoField.MINUTE_OF_HOUR) //分.appendLiteral(":").appendValue(ChronoField.SECOND_OF_MINUTE) //秒.appendLiteral(".").appendValue(ChronoField.MILLI_OF_SECOND) //毫秒.toFormatter();String str = "2013/1/2 8:1:10.777";LocalDateTime dateTime = LocalDateTime.parse(str, matter);// 2013-01-02T08:01:10.777System.out.println(dateTime);
时间转换
jdk8 之前
注意 int 溢出
Date today = new Date();// 注意加 L |Date nextMonth = new Date(today.getTime() + 30L * 1000 * 60 * 60 * 24);System.out.println(today);System.out.println(nextMonth);
推荐
Calendar c = Calendar.getInstance();c.setTime(new Date());c.add(Calendar.DAY_OF_MONTH, 30);System.out.println(c.getTime());
jdk8
api 进行日期计算
System.out.println(LocalDate.now()// 减少一天的三种方式.minus(Period.ofDays(1)).minus(1, ChronoUnit.DAYS).minusDays(1));
with() + TemporalAdjusters 进行日期调节
使用 TemporalAdjusters.firstDayOfMonth 得到当前月的第一天;
使用 TemporalAdjusters.firstDayOfYear() 得到当前年的第一天;
使用 TemporalAdjusters.previous(DayOfWeek.SATURDAY) 得到上一个周六;
使用 TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY) 得到本月最后一个周五。
with() + lambda 表达式进行自定义的时间调整
System.out.println(LocalDateTime.now().with((time) -> {time.plus(1, ChronoUnit.DAYS);return time;}));
query() + lambda 表达式进行日期筛选
todo
计算时间差
System.out.println(ChronoUnit.MINUTES.between(LocalDateTime.now(),LocalDateTime.now().plus(1, ChronoUnit.DAYS)));
