JSON日期到Java日期? [英] JSON date to Java date?

查看:154
本文介绍了JSON日期到Java日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无处可寻。我从返回标准JSON日期的API中获取一些JSON。您可以通过在JavaScript控制台中运行此代码来查看格式:

I could not find this anywhere. I fetch some JSON from an API that returns standard JSON dates. You can see the format by running this code in a JavaScript console:

> new Date().toJSON();
"2010-10-27T11:58:22.973Z"

嗯,实际上,我正在使用的API没有返回毫秒部分,有时它会返回一个时区而不是 Z ,因此日期可能看起来像以下任何一个:

Well, actually, the API I'm working with is not returning the millisecond part, and sometimes it returns a timezone instead of Z, so dates can look like any one of these:


  • 2010-10-27T11:58:22Z

  • 2010-10-27T11:58:22 + 03:00

  • 2010-10-27T11:58:22Z
  • 2010-10-27T11:58:22+03:00

解析这些日期有点麻烦。有没有办法解析这些日期,使用 org.json

Parsing these kinds of dates is somewhat cumbersome. Is there any way to parse these kinds of dates, using org.json?

我目前的解决方案是:

public static Date parseDateTime(String dateString) {
    if (dateString == null) return null;
    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
    if (dateString.contains("T")) dateString = dateString.replace('T', ' ');
    if (dateString.contains("Z")) dateString = dateString.replace("Z", "+0000");
    else
        dateString = dateString.substring(0, dateString.lastIndexOf(':')) + dateString.substring(dateString.lastIndexOf(':')+1);
    try {
        return fmt.parse(dateString);
    }
    catch (ParseException e) {
        Log.e(Const.TAG, "Could not parse datetime: " + dateString);
        return null;
    }
}

唉!

推荐答案

该DateTime格式实际上是ISO 8601 DateTime。 JSON没有为日期/时间指定任何特定格式。如果你有点谷歌,你会发现很多实现用Java来解析它。

That DateTime format is actually ISO 8601 DateTime. JSON does not specify any particular format for dates/times. If you Google a bit, you will find plenty of implementations to parse it in Java.

这是一个

如果你愿意使用Java内置日期/时间/日历以外的东西课程,我也建议 Joda Time 。他们提供(在许多方面) ISODateTimeFormat 解析这些类型的字符串。

If you are open to using something other than Java's built-in Date/Time/Calendar classes, I would also suggest Joda Time. They offer (among many things) a ISODateTimeFormat to parse these kinds of strings.

这篇关于JSON日期到Java日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆