如何以微秒为单位解析日期字符串 [英] How to parse a date string with microseconds

查看:103
本文介绍了如何以微秒为单位解析日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些日期时间字符串,例如

I have some datetime string e.g.

"2017-10-29T02:54:03.125983+00:00"
"2017-10-29T02:09:22.1453833+00:00"

具有6或7个数字长度毫秒,如何将其解析为d3 JavaScript语言中的日期对象?我尝试过

with 6 or 7 digital length milliseconds, how can I parse it to date object in d3 javascript language? I have tried

d3.timeParse("%Y-%m-%dT%H:%M:%S.%LZ"); 

但失败,它返回null

but failed, it returns null

推荐答案

您拥有的不是毫秒 ,而是微秒 strong>.

What you have is not a long millisecond: that is a microsecond.

自D3 v4起,D3中有一个说明符,持续了微秒(请参见此处).要解析微秒,请使用"f".根据API:

There is a specifier in D3 for microseconds since D3 v4 (see here). To parse microseconds, use "f". According to the API:

%f-微秒,十进制数字[000000,999999].

%f - microseconds as a decimal number [000000, 999999].

这里是带有您的字符串的演示(不要查看Stack代码段控制台,单击运行代码段"并打开浏览器控制台以查看实际日期):

Here is a demo with your string (don't look at the Stack snippet console, click "Run code snippet" and open your browser console to see the actual date):

var date = "2017-10-29T02:54:03.125983+00:00";
var parser = d3.timeParse("%Y-%m-%dT%H:%M:%S.%f%Z"); 
console.log(parser(date))

<script src="https://d3js.org/d3-time-format.v2.min.js"></script>

三个观察结果:

  1. 与自己的API所说的相反,"f"与默认捆绑包一起使用.您必须参考独立时间微库(请查看上面的演示以查看URL).让我们证明一下:
  1. Contrary to what the own API says, "f" will not work with the default bundle. You have to reference the standalone time microlibrary (have a look at my demo above to see the URL). Lets prove it:

var date = "2017-10-29T02:09:22.145383+00:00";
var parser = d3.timeParse("%Y-%m-%dT%H:%M:%S.%f%Z"); 
console.log(parser(date))

<script src="https://d3js.org/d3.v4.min.js"></script>

  1. 删除该"Z".它应该是"%Z".正如API所说,请注意,此处的文字Z与时区偏移量指令%Z不同" ;
  2. 没有7位数的微秒.必须是6位数字.
  1. Remove that "Z". It should be "%Z" instead. As the API says, "Note that the literal Z here is different from the time zone offset directive %Z";
  2. There is no microsecond with 7 digits. It has to be 6 digits.

标题已编辑.

这篇关于如何以微秒为单位解析日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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