如何将LocalDate转换为特定的日期-时间格式



如何在java 中将ISO_LOCAL_DATE转换为日期-时间格式:yyyy-MM-dd'TH:MM:ss.SSSZ

例如:给出日期:2016-01-25至2016-01-25T000:00:00.000+0100

我假设你有一个字符串,例如2016-01-25,并且你想要一个包含JVM默认时区中一天开始的字符串(这个问题不清楚(。我首先为您想要的格式定义一个格式化程序(它是ISO8601(:

private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSxx");

现在你的转换开始了:

String isoLocalDateString = "2016-01-25";
LocalDate date = LocalDate.parse(isoLocalDateString);
ZonedDateTime dateTime = date.atStartOfDay(ZoneId.systemDefault());
String dateTimeString = dateTime.format(formatter);
System.out.println(dateTimeString);

当在我的时区欧洲/哥本哈根运行时,这个示例代码的输出就是您所要求的:

2016-01-25T000:00:00.000+0100

在极少数情况下,夏季时间(DST(从一天的第一刻开始,一天中的时间不会是00:00:00.000。

对于使用ISO_LOCAL_DATE进行解析,我们不需要指定格式化程序,因为此格式化程序是LocalDate.parse()的默认格式化程序。

所有这些都表明,您通常不应该希望将日期从一种字符串格式转换为另一种字符串形式。在程序中,将日期保存为LocalDate对象。当您获得字符串输入时,解析为LocalDate。只有当您需要提供字符串输出时,例如在与另一个系统的数据交换中,才可以按所需格式格式化为字符串。

链接:维基百科文章:ISO 8601

LocalDate上有各种方法,包括:

  • LocalDate::toDateTimeAtCurrentTime((
  • LocalDate::toDateTimeAtStartOfDay((
  • LocalDate::toDateTime(LocalTime(
  • LocalDate::toDateTime(LocalTime,DateTimeZone(

它就像LocalDateTime localDateTime = yourLocalDate.atStartOfDay()一样简单

更新添加时间戳很简单:

ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime = zdt = localDateTime.atZone(zoneId);

可以组合为

ZonedDateTime zdt = yourLocalDate.atStartOfDay().atZone(ZoneId.of("America/New_York"));

最新更新