【问题标题】:How to correctly convert a timestring to a date object如何正确地将时间字符串转换为日期对象
【发布时间】:2012-12-16 13:32:34
【问题描述】:

我在将时间字符串转换为准确的 Date 对象表示时遇到问题

我正在与之通信的服务器将提供这样的 UTC 时间值。

2013-01-02T05:32:02.8358602Z

当我尝试以下代码时,我得到的毫秒计数比预期的 UTC 提前了近 2 小时 15 分钟。

DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.getDefault());
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));                   
Date date = inputFormat.parse("2013-01-02T05:32:02.8358602Z");

我做错了什么

【问题讨论】:

标签: java android epoch


【解决方案1】:

问题是 SimpleDateFormat 需要 8358602 不是一秒钟的时间,如果millis = 8358602 ms,它就是数字。默认情况下,SimpleDateFormat 处于“宽松”模式,这就是它接受 8358602 的原因,它还将接受天字段中的 99 并将额外的天数移至月份字段等等。如果您将严格模式切换为 SimpleDateFormat.setLenient(true),您将收到 ParseException,因为 millis 的最大值为 999。

我可以提供一种解决方法。您的日期采用带有小数秒的 W3C XML Schema 1.0 日期/时间格式。对于这种情况,您需要 javax.xml.datatype.XMLGregorianCalendar。这行得通

DatatypeFactory dtf = DatatypeFactory.newInstance();
XMLGregorianCalendar c = dtf.newXMLGregorianCalendar("2013-01-02T05:32:02.8358602Z");
System.out.println(c.toGregorianCalendar().getTime());

和打印

Wed Jan 02 07:32:02 EET 2013

请注意,EET 是 GMT+2

【讨论】:

  • 感谢您的解释。
【解决方案2】:

试试这个:

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);

必须在 SimpleDateFormat() 构造函数中指定正确的格式。

已编辑:

public String getconvertdate1(String date)
{
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
    inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
    Date parsed = null; // should not be initialized first else current date will be printed in case of a parse exception
    try
    {
        parsed = inputFormat.parse(date);
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String outputText = outputFormat.format(parsed);
    return outputText;
}

也可以用我上面的方法试试这个格式:EEE MMM dd HH:mm:ss zzz yyyy

【讨论】:

  • 不幸的是引发了解析异常
  • 我曾与此合作过,Jayamohan....@Redshirt,我发布了另一个答案,请参阅,已编辑。
  • 我用输入调用了你的方法 getconvertdate1("2013-01-02T05:32:02.8358602Z"); 仍然得到 java.text.ParseException
  • 在使用编辑后的答案时,将“T”添加到 inputFormat 有效。与我的代码相比,您的代码唯一真正的区别是您在分配给它之前实例化了 Date 对象......不会尝试找出原因,只是很高兴它可以工作。
  • @Jayamohan:你看不到上面指定的格式......它的“EEE MMM dd HH:mm:ss zzz yyyy”并且你指定的是“YYYY MM DD HH:MM:SS”我认为.....你可以按照你的日期模式,为此你必须在 SimpleDateFormat() 的构造函数中指定正确的格式......
猜你喜欢
  • 2021-08-16
  • 2023-04-09
  • 2014-12-13
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多