java datetimeformatter的用法是什么

Java的DateTimeFormatter类是用来格式化日期和时间的工具类。它提供了一组预定义的格式化模式,可以将日期和时间对象格式化为字符串,也可以将字符串解析为日期和时间对象。

DateTimeFormatter的用法如下:

创建DateTimeFormatter对象:可以使用ofPattern()方法创建DateTimeFormatter对象,指定日期和时间的格式模式。例如:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”);

格式化日期和时间对象:可以使用format()方法将日期和时间对象格式化为字符串。例如:
LocalDateTime dateTime = LocalDateTime.now();
String formattedDateTime = formatter.format(dateTime);

解析字符串为日期和时间对象:可以使用parse()方法将字符串解析为日期和时间对象。例如:
String strDateTime = “2021-01-01 12:00:00”;
LocalDateTime parsedDateTime = LocalDateTime.parse(strDateTime, formatter);

自定义格式模式:可以使用预定义的格式模式来格式化日期和时间,也可以自定义格式模式。例如:
DateTimeFormatter customFormatter = DateTimeFormatter.ofPattern(“dd/MM/yyyy”);
LocalDate date = LocalDate.now();
String formattedDate = customFormatter.format(date);

使用DateTimeFormatter的其他方法:DateTimeFormatter还提供了一些其他的方法,如withLocale()可以设置本地化信息,withZone()可以设置时区信息等。

需要注意的是,DateTimeFormatter是线程安全的,可以在多个线程中共享使用。同时,它也是不可变的,一旦创建就不可修改。

阅读剩余
THE END