Java 8添加了一个新的java.time用于处理日期和时间的API(JSR 310)
我将日期和时间作为字符串(例如“2014-04-08 12:30”)。如何获得LocalDateTime来自给定字符串的实例
使用完LocalDateTime对象后:如何将LocalDateTime实例转换回与上面所示格式相同的字符串
解析日期和时间
要从字符串创建LocalDateTime对象,可以使用staticLocalDateTime.parse()方法。它需要一个字符串和一个DateTimeFormatter作为参数。DateTimeFormatter用于指定日期/时间模式
字符串str=“1986-04-08 12:30”;
DateTimeFormatter formatter=模式的DateTimeFormatter.of(“yyyy-MM-dd-HH:MM”);
LocalDateTime dateTime=LocalDateTime.parse(str,格式化程序);
格式化日期和时间
要创建格式化字符串并输出LocalDateTime对象,可以使用format()方法
DateTimeFormatter formatter=DateTimeFormatter.of模式(“yyyy-MM-dd-HH:MM”);
LocalDateTime dateTime=LocalDateTime.of(1986年4月8日、12日、30日);
字符串formattedDateTime=dateTime.format(格式化程序);//"1986-04-08 12:30"
请注意,在DateTimeFormatter中,有一些常用的日期/时间格式预定义为常量。例如:从上面使用DateTimeFormatter.ISO\u DATE\u TIME格式化LocalDateTime实例将导致字符串“1986-04-08T12:30:00”
parse()和format()方法可用于所有与日期/时间相关的对象(例如LocalDate或ZonedDateTime)