Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java toDate()返回的日期不准确_Java_Android_Date_Jodatime - Fatal编程技术网

Java toDate()返回的日期不准确

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

我正在使用JODA格式化类型为:2012-01-05T08:00:00.000Z(2012年1月5日)的日期,并尝试将其转换为Java日期

以下是我在现阶段采取的步骤:

  • 使用DateTimeFormatter进行初始格式化:

    DateTimeFormatter jodaParser = DateTimeFormat
                                .forPattern(inputDateWhichIsAString);
    
  • 将其转换为具有必要时区(UTC)的LocalDate

  • 使用LocalDate检索Java日期对象

    return localDate.toDate();
    
然而,虽然我希望返回的日期是:2012年1月5日,但我得到的是1970年1月1日。我的印象是JODA负责处理Java日期对象已知的这些问题

我在这里做错了什么吗?或者你们中有人有过类似的问题并且知道解决方法吗

谢谢 拉贾特

编辑:

首先谢谢迈克尔

因此,与我之前的代码片段相比,这里有一个改进,它确保了我得到了正确的日期——换句话说,就是解决方案


    //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;