我有这个密码
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'-'hh:mm")
DateTime dateTime1 = new DateTime()
println("dateTime1 : " + dateTime1)
DateTime formattedDate = fmt.parseDateTime(dateTime1.toString());
println("formattedDate : " + formattedDate)
DateTimeFormatter finalFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm'-'hh:mm");
System.out.println("formatted date : " + finalFormat.print(formattedDate));它打印出这样的东西:
dateTime1 : 2014-08-20T15:34:17.256-04:00
formattedDate : 2014-08-20T16:00:17.256-04:00
formatted date : 2014-08-20T16:00-04:00我想要一个精确的日期格式(因为这是要求)
2014-08-20T15:34-04:00问题在于
formattedDate : 2014-08-20T16:00:17.256-04:00
formatted date : 2014-08-20T16:00-04:00它总是打印出“16:00-04:00”。
我怎么弄到那个?从将转换为DateTime对象的数据库中检索日期。
当我尝试这个:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
DateTime dateTime1 = new DateTime()
println("dateTime1 : " + dateTime1)
DateTime formattedDate = fmt.parseDateTime(dateTime1.toString());
println("formattedDate : " + formattedDate)
DateTimeFormatter finalFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm'-'hh:mm");
System.out.println("formatted date : " + finalFormat.print(formattedDate));产出变化:
dateTime1 : 2014-08-20T15:59:34.876-04:00
formattedDate : 2014-08-20T15:59:34.876-04:00
formatted date : 2014-08-20T15:59-03:59应该是-04.00。但结果却是“-03:59”,这是一辆马车。
任何帮助都是非常感谢的。
谢谢
发布于 2014-08-20 19:54:48
您的时间格式是不正确的,更具体地说,最后一部分是将时区解析为一天中的时间(小时和分钟)。试着用这个代替:
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")发布于 2014-08-20 19:51:59
问题在于你的模式
"yyyy-MM-dd'T'HH:mm'-'hh:mm"当您添加'hh:mm‘,您将再次阅读时间为04:00,然而,由于它已经读到它是一个下午的时间,这是16:00。您应该将时区读入带有Z的时差,而不是作为时间本身的一部分。
从Javadoc到DateTimeFormat
Symbol Meaning Presentation Examples
------ ------- ------------ -------
Z time zone offset/id zone -0800; -08:00; America/Los_Angeles和
Zone: 'Z' outputs offset without a colon, 'ZZ' outputs the offset with a colon, 'ZZZ' or more outputs the zone id.我建议你用
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ")注意:末尾的-不是分隔符,而是减号。我猜-04:00时区就是AEST时区。
发布于 2014-08-20 19:56:52
您的偏移格式不正确,ZZ是带冒号的时区,您需要添加withOffsetParsed() -
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mmZZ");
String dateTime1 = "2014-08-20T15:34-04:00";
DateTime formattedDate = fmt.withOffsetParsed().parseDateTime(dateTime1);
System.out.println("formattedDate : " + formattedDate);
System.out.println("formatted date : " + fmt.print(formattedDate));输出是
formattedDate : 2014-08-20T15:34:00.000-04:00
formatted date : 2014-08-20T15:34-04:00从javadoc,
区域:没有冒号的“Z”输出偏移量,“ZZ”用冒号输出偏移量,“ZZZ”或更多输出区域id。
https://stackoverflow.com/questions/25413110
复制相似问题