JavaScript将字符串转换为日期时间 [英] JavaScript convert string to date time

查看:584
本文介绍了JavaScript将字符串转换为日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下格式的日期时间的字符串

I have a string that contains a datetime in the following format

2016-07-30 00:00:01.0310000

我需要将其转换为JavaScript中保留亚秒的datetime对象。

I need to convert this to a datetime object in JavaScript retaining the sub-seconds.

如果我使用

var d = new Date('2016-07-30 00:00:01.0310000');

删除01之后的所有内容,如何有效实现?

Everything after 01 is dropped, how can I efficiently achieve this?

推荐答案

您必须自己解析该字符串(这很简单,唯一棘手的位是在毫秒值上尾随零),然后使用 Date(年,月,日,小时,分钟,秒,毫秒)构造函数。或使用库和格式字符串。

You'll have to parse the string yourself (which is quite simple, the only tricky bit is trailing zeros on the milliseconds value) and build the date using the Date(years, months, days, hours, minutes, seconds, milliseconds) constructor. Or use a library and a format string.

下面是一个示例:

var str = "2016-07-30 00:00:01.0310000";
var parts = /^\s*(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d+)\s*$/.exec(str);
var dt = !parts ? null : new Date(
    +parts[1],                   // Years
    +parts[2] - 1,               // Months (note we start with 0)
    +parts[3],                   // Days
    +parts[4],                   // Hours
    +parts[5],                   // Minutes
    +parts[6],                   // Seconds
    +parts[7].replace(/0+$/, '') // Milliseconds, dropping trailing 0's
);
if (dt.toISOString) {
  console.log(dt.toISOString());
} else {
  console.log("date", dt.toString());
  console.log("milliseconds", dt.getMilliseconds());
}

在正则表达式中, \d 表示数字, {x} 表示重复x次。

In the regex, \d means "a digit" and {x} means "repeated x times".

!部分? null:新的Date(...)位是这样,如果字符串与格式不匹配,我们将得到 null 而不是错误

The !parts ? null : new Date(...) bit is so that if the string doesn't match the format, we get null rather than an error.

这篇关于JavaScript将字符串转换为日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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