欢迎光临
感受代码之美

Java 8中使用LocalDate/LocalTime/LocalDateTime获取日期时间

获取年月日

示例代码:

// current date
LocalDate localDate = LocalDate.now();
System.out.println("Current date is:");
System.out.println(localDate.getYear());
System.out.println(localDate.getMonth());
System.out.println(localDate.getDayOfMonth());
System.out.println(localDate.get(ChronoField.MONTH_OF_YEAR));
// Date format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
System.out.println(localDate.format(dateTimeFormatter));

// specific date
System.out.println("Specific date is:");
LocalDate specificDate = LocalDate.of(2018,10,23);
System.out.println(specificDate.format(dateTimeFormatter));

// TemporalAdjusters static method
LocalDate anothorLocalDate = localDate.with(firstDayOfYear());
System.out.println(anothorLocalDate.format(dateTimeFormatter));

打印结果如下:

Current date is:
2019
OCTOBER
23
10
2019-10-23
Specific date is:
2018-10-23
2019-01-01

获取时分秒

 // current time
LocalTime localTime = LocalTime.now();
System.out.println("Current time is:");
System.out.println(localTime.getHour());
System.out.println(localTime.getMinute());
System.out.println(localTime.get(ChronoField.MINUTE_OF_HOUR));
// Time format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("hh:mm:ss");
System.out.println(localTime.format(dateTimeFormatter));

// specific time
System.out.println("Specific time is:");
LocalTime specificTime = LocalTime.of(9,35,23);
System.out.println(specificTime.format(dateTimeFormatter));

获取年月日时分秒

 // current time
LocalDateTime localDateTime = LocalDateTime.now();
// Time format
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
System.out.println(localDateTime.format(dateTimeFormatter));

References

  1. Class TemporalAdjusters
  2. 为什么不建议使用Date,而是使用Java8新的时间和日期API?
  3. Class DateTimeFormatter
转载请注明来源:四个空格 » Java 8中使用LocalDate/LocalTime/LocalDateTime获取日期时间

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址