Java toDate()返回的日期不准确
我正在使用JODA格式化类型为:2012-01-05T08:00:00.000Z(2012年1月5日)的日期,并尝试将其转换为Java日期 以下是我在现阶段采取的步骤:Java toDate()返回的日期不准确,java,android,date,jodatime,Java,Android,Date,Jodatime,我正在使用JODA格式化类型为:2012-01-05T08:00:00.000Z(2012年1月5日)的日期,并尝试将其转换为Java日期 以下是我在现阶段采取的步骤: 使用DateTimeFormatter进行初始格式化: DateTimeFormatter jodaParser = DateTimeFormat .forPattern(inputDateWhichIsAString); 将其转换为具有必要时区(UTC)的Local
- 使用DateTimeFormatter进行初始格式化:
DateTimeFormatter jodaParser = DateTimeFormat .forPattern(inputDateWhichIsAString);
- 将其转换为具有必要时区(UTC)的LocalDate
- 使用LocalDate检索Java日期对象
return localDate.toDate();
//Make sure you use HH instead of hh if you are using 24 hour convention. I use this convention since my date format is: 2012-01-05T08:00:00.000Z
DateTimeFormatter jodaParser =
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDate date = jodaParser.withZone(DateTimeZone.UTC).parseDateTime
(inputDateWhichIsAString).toLocalDate();
return date.toDate();
干杯
Rajat
DateTimeFormat.forPattern
期望,顾名思义,一个模式而不是一个要转换的输入。只有DateTimeFormatter.parseDateTime(字符串)需要字符串解析实际数据
因此,在DateTimeFormat.forPattern的字符串中,必须传递一个formatstring。根据您的输入,请使用此处描述的格式符号:),因为我们都喜欢较短的解决方案: 考虑到我的日期格式是JODA定义的ISODateFormat类型之一,我的问题的更简单解决方案是:
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dateTime = fmt.parseDateTime(inputDateWhichIsAString);
if (dateTime != null) {
Date date = dateTime.toDate();
}
return date;
+1对于残酷的命名约定blubWhichIsAString:)@Michael:请原谅我的挫折:请确保您的代码的格式和查看方式正确,从而使其易于阅读和遵循。我没有测试代码,但可以清楚地看到,return语句所在的行中没有定义“date”。
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime dateTime = fmt.parseDateTime(inputDateWhichIsAString);
if (dateTime != null) {
Date date = dateTime.toDate();
}
return date;