【发布时间】:2018-07-03 18:37:30
【问题描述】:
我需要为 SAP PI 编写一个 java 函数,它为我的 XML 映射返回一个字符串,格式为:yyyy-MM-dd T HH:mm:ss(例如,2018-08-15T00:00:00)即使我的源字段只是没有时间的日期字段(例如,2018-08-15)。
我已经尝试了SimpleDateFormat Java 类,但我无法让它工作。有没有一种简单的方法可以做到这一点?
在建议的帖子(答案/重复/链接)中,我找不到我要找的东西。我想我没有让自己清楚地描述问题,但问题是我从源 XML (SAP PO) 获取日期,我需要将其转换为目标 XML 中的 ISO 8601 日期。
感谢 Ole,我想出了以下“初学者”功能(为了完整性):
public String DH_FormatDateTimeStringB(String ndate, String npattern, Container container) throws StreamTransformationException{
//This function gets a date from the IDOC and returns it as a datetime string in ISO 8601 (ISO 8601 Representation of dates and times
//in information interchange required. Ex: npattern = "yyyy-MM-dd")
DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern(npattern);
LocalDate date = LocalDate.parse(ndate, formatterDate);
//Convert date to datetime
LocalDateTime localDateTime1 = date.atStartOfDay();
//System.out.println(localDateTime1.toString());
return localDateTime1.toString();
}
因为它现在只需要一个没有时间的日期,它可能会使用“StartOfDay”。也许我稍后会调整它以查看字符串中是否有时间部分。
感谢大家的帮助!
【问题讨论】:
-
不,你没有。您需要找到一个好的日期时间库,并使用它。永远不要自己动手:你不知道约会有多疯狂。即使在了解了疯狂的约会是如何变得如此之后。
-
是的,
DatetimeFormat.ISO_FORMAT.format(yourDatetime) -
不要使用
SimpleDateFormat,它不仅过时了,而且出了名的麻烦。而是使用java.time, the modern Java date and time API。顺便说一句,您忘记向我们展示您的尝试以及它是如何失败的。 -
搜索java.time类
LocalDateTime。 -
假设
yourDate是LocalDate,使用yourDate.atStartOfDay().toString()。它给出了一个类似2018-11-29T00:00的字符串。它没有几秒钟,但符合 ISO 8601 标准,因此应该在您的 XML 和 SAP 中工作。如果没有,您将需要使用yourDate.atStartOfDay().format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss"))。
标签: java sap iso8601 sap-xi sap-pi