将Java OffsetDateTime解析为JS日期

时间:2018-11-09 15:59:11

标签: javascript node.js datetime java-time

在我的基于JS的微服务中,我莫名其妙地从内部使用OffSetDateTime的Java微服务中获取以下JSON。

{
   "eventTime":   "eventTime":{
      "offset":{
         "totalSeconds":0,
         "id":"Z",
         "rules":{
            "fixedOffset":true,
            "transitions":[

            ],
            "transitionRules":[

            ]
         }
      },
      "year":2018,
      "month":"NOVEMBER",
      "dayOfMonth":9,
      "dayOfWeek":"FRIDAY",
      "dayOfYear":313,
      "monthValue":11,
      "hour":5,
      "minute":57,
      "second":21,
      "nano":716000000
   }
}

而不是

{"eventTime" :"2018-11-09T05:57:21.716Z" }

如何在JS中解析此内容?下面给我NaN

Date.parse(eventTime)

eventTime是上面提到的第一个字符串。

1 个答案:

答案 0 :(得分:0)

您需要手动解析它。这样的事情会起作用:

var res = {
   "eventTime":{
      "offset":{
         "totalSeconds":0,
         "id":"Z",
         "rules":{
            "fixedOffset":true,
            "transitions":[

            ],
            "transitionRules":[

            ]
         }
      },
      "year":2018,
      "month":"NOVEMBER",
      "dayOfMonth":9,
      "dayOfWeek":"FRIDAY",
      "dayOfYear":313,
      "monthValue":11,
      "hour":5,
      "minute":57,
      "second":21,
      "nano":716000000
   }
};
var d = new Date(
  res.eventTime.year, 
  res.eventTime.monthValue - 1, 
  res.eventTime.dayOfMonth, 
  res.eventTime.hour, 
  res.eventTime.minute, 
  res.eventTime.second,
  res.eventTime.nano/1000000
);

alert(d.getTime());

Javascript不支持纳秒。它仅支持长达毫秒的粒度。

另外,月份是从0 - 11开始的,因此,您需要对案件中的月份值进行value - 1