将格式为YYYYMMDDHHMMSS的字符串转换为JavaScript Date对象 [英] Converting a string formatted YYYYMMDDHHMMSS into a JavaScript Date object

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

问题描述

我有一个字符串,其中的日期格式如下:YYYYMMDDHHMMSS。我想知道如何使用JavaScript将其转换为JavaScript Date对象。

I have a string with a date in it formatted like so: YYYYMMDDHHMMSS. I was wondering how I would convert it into a JavaScript Date object with JavaScript.

预先感谢!

推荐答案

如何以一种古怪的方式做到这一点呢?

How about this for a wacky way to do it:

var date = new Date(myStr.replace(
    /^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/,
    '$4:$5:$6 $2/$3/$1'
));

零外部库,一行代码;-)

Zero external libraries, one line of code ;-)

原始方法的说明:

// EDIT: this doesn't work! see below.
var date = Date.apply(
    null,
    myStr.match(/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/).slice(1)
);

match()函数(之后已经被 slice() d包含在右边)将返回一个包含年,月,日,时,分和秒的数组。这恰好是Date构造函数的正确顺序。 Function.apply 是一种使用数组中的参数调用函数的方法,因此我使用了 Date.apply(< that array>)

The match() function (after it has been slice()d to contain just the right) will return an array containing year, month, day, hour, minute, and seconds. This just happens to be the exact right order for the Date constructor. Function.apply is a way to call a function with the arguments in an array, so I used Date.apply(<that array>).

例如:

var foo = function(a, b, c) { };

// the following two snippets are functionally equivalent
foo('A', 'B', 'C')

var arr = ['A', 'B', 'C'];
foo.apply(null, arr);

我刚刚意识到此功能实际上不起作用,因为javascript的月份为零,索引。您仍然可以使用类似的方法来执行此操作,但是需要执行一个中间步骤,即在将数组传递给构造函数之前从数组中减去一个。我将其留在此处,因为评论中已对其进行了询问。

I've just now realised that this function doesn't actually work, since javascript months are zero-indexed. You could still do it in a similar method, but there'd be an intermediate step, subtracting one from the array before passing it to the constructor. I've left it here, since it was asked about in the comments.

其他选项仍然可以正常工作。

The other option works as expected however.

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

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