java8 对date的支持更加好,更加清晰,不用再在calendar和date之间纠结了。
LocalDateTime datetime = LocalDateTime.now(); // datetime 如: 2024-11-13T11:36:44.135
LocalDate date = LocalDate.now(); // date 如:2024-11-13 (所以,如果要年月日用这个格式就可以)
LocalTime time = LocalTime.now(); // time 如:11:36:44.135
System.out.println("datetime: "+datetime);
System.out.println("date: "+date);
System.out.println("time: "+time);
//不用calendar来会转换了,月分为枚举值,有value,有string,更清晰
Month month = datetime.getMonth(); // 月 JANUARY
int monthValue = datetime.getMonthValue();// 月value 1,
System.out.println(month);
System.out.println(monthValue);
DayOfWeek dayOfWeek = datetime.getDayOfWeek(); //week 如: SUNDAY
System.out.println(dayOfWeek);
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 0b1100, 10, 43, 20);// 新建datetime
LocalDate localDate = LocalDate.of(2020, 1, 12); // 根据年月日新建date
LocalTime localTime = LocalTime.of(10, 43, 20); // 根据时分秒新建time
System.out.println(localDateTime); // 格式如: 2020-01-12T10:43:20
System.out.println(localDate); // 格式如: 2020-01-12
System.out.println(localTime); // 格式如: 10:43:20
Instant now = Instant.now();
long epochSecond = now.getEpochSecond(); // 秒long
long EpochMilli = now.toEpochMilli(); // 毫秒long
System.out.println(epochSecond);
System.out.println(EpochMilli);
生成datetime格式的字符串
代码:
public static String generateDateTimeStringByMinusOffset(int offset){
LocalDateTime date = LocalDateTime.now();
LocalDateTime startDate= date.minusDays(offset);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtil.DEFAULT_FORMAT);
return startDate.format(formatter);
}
注: DateUtil.DEFAULT_FORMAT 是 "yyyy-MM-dd HH:mm:ss"
生成date格式的字符串
注: LocalDate date = LocalDate.now(); 直接就可以拿到当前时间的字符串。
但是如果要计算时间,则不太好用,所以推荐用LocalDateTime,比较通用。
代码:
public static String generateDateStringByMinusOffset(int offset){
LocalDateTime date = LocalDateTime.now();
LocalDateTime startDate= date.minusDays(offset);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtil.DATE_FORMAT);
return startDate.format(formatter);
}
注:DateUtil.DATE_FORMAT是 "yyyy-MM-dd"