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"

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

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

啊!

推荐答案

该日期时间格式实际上是ISO 8601日期时间.JSON没有为日期/时间指定任何特定格式.如果您稍微搜索一下,就会发现有很多用Java解析它的实现.

Here's one

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相关问答推荐

Jolt将键和值转换为单独的数组集

如何在VegaLite中应用Times New Roman,CaliBiri字体

在PowerShell中,如何获取数据对所在的JSON对象的名称

如何让JSON子查询在没有行的情况下返回空数组而不是NULL

如何使用jq按键 Select 并获取整个json输出来更改json中的多个值

Delphi 11.3无法从变体创建/添加JSON

基于JQ中另一个对象的值 Select 对象

取消嵌套数组并将数组名称添加为附加字段

如何在 Apps 脚本中循环遍历 JSON 响应

无法使用 vue.js 访问 JSON 数组的项目

向 JSON 文件添加注释

字典和对象的模型创建问题

单元测试球衣 Restful Services

将 JSON 读取到 pandas 数据框 - ValueError:将 dicts 与非系列混合可能会导致排序不明确

将 JSON 数据导入 Google 表格

如何向(JSON)对象的原型添加方法?

如何在 Django JSONField 数据上聚合(最小/最大等)?

Swift :将 struct 转换为 JSON?

雅虎财经全币种报价 API 文档

ASP.NET Web API JSON 输出中没有时间的日期