如何在日期和时间字符串中添加几分钟或几天



鉴于我有一个类似String addTimestamp = 2021-05-01T00:00:00+02:00的字符串,我希望在他的约会中增加几分钟或几天。

我目前增加3天的解决方案是:

ZonedDateTime result = ZonedDateTime.parse(addTimestamp, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
String removeTimestamp = result.plusDays(3).toString();
System.out.println("addTimestamp:    " + addTimestamp);
System.out.println("removeTimestamp: " + removeTimestamp);

这工作得很好,但它打破了格式:

addTimestamp:    2021-05-01T00:00:00+02:00
removeTimestamp: 2021-05-04T00:00+02:00

如您所见,removeTimestamp中的秒数已错过。我该怎么修?

您需要将ZonedDateTime格式化为正确的格式。仅仅对其调用toString((就会产生不希望的结果:

您可以使用DateTimeFormatter的ISO_OFFSET_DATE_TIME进行解析,也可以使用它将格式设置回字符串:https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(date));

您也可以直接在ZonedDateTime上使用format()方法:

result.plusDays(3).format(DateTimeFormatter.ISO_DATE_TIME)

最新更新