简体   繁体   English

如何在Javascript中将短日期转换为长日期?

[英]How can I convert a short date to a long date in Javascript?

I need to convert 04/06/13 (for example) to a long date - Tue Jun 04 2013 00:00:00 GMT+0100 (BST) . 我需要将04/06/13 (例如)转换为长日期- 2013年6月4日星期二00:00:00 GMT + 0100(BST) How can I do this using Javascript? 如何使用Javascript执行此操作? I know how to convert a long date to a short date - just not the other way round. 我知道如何将长日期转换为短日期-而不是相反。

You could try the parsing functionality of the Date constructor , whose result you then can stringify : 您可以尝试使用Date构造 函数解析功能 ,然后可以将其结果字符串化

> new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200" // or something

But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY format correctly. 但是解析是依赖于实现的,并且不会有很多引擎能够正确解释您的奇数DD/MM/YY格式。 If you had used MM/DD/YYYY , it probably would be recognized everywhere. 如果您使用MM/DD/YYYY ,那么它可能会在任何地方被识别。

Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor: 相反,您想确保它的解析方式,因此必须自己完成并将单个部分输入构造函数中:

var parts = "04/06/13".split("/"),
    date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200

An alternative to the split method, uses lastIndexof and slice instead, to change the year to ISO8601 format which then gives a non-standard string that is known to be working across browsers, and then uses the date parsing method . 拆分方法的替代方法是使用lastIndexof和slice,将年份更改为ISO8601格式,然后提供一个已知可跨浏览器使用的非标准字符串,然后使用日期解析方法 (assuming a fixed pattern like in question) (假设有问题的固定模式)

However, 然而,

If you want to ensure how it is parsed, you have to do it yourself and feed the single parts into the constructor: 如果要确保它的解析方式,则必须自己完成并将单个部分输入到构造函数中:

, this would mean using the split method, see @Bergi answer . ,这意味着使用split方法, 请参见@Bergi answer

var string = "04/06/13",
    index = string.lastIndexOf("/") + 1,
    date = new Date(string.slice(0, index) +  (2000 + parseInt(string.slice(index), 10)));

console.log(date);

Output 输出量

Sat Apr 06 2013 00:00:00 GMT+0200 (CEST) 

On jsfiddle jsfiddle上

or a further alternative would be to use moments.js 或其他替代方法是使用moments.js

var string = "04/06/13";

console.log(moment(string, "DD/MM/YY").toString());

Output 输出量

Sat Apr 06 2013 00:00:00 GMT+0200 (CEST) 

On jsfiddle jsfiddle上

You can use: 您可以使用:

new Date(2013, 06, 04)

...or directly using a date string (ie a string representing a date as accepted by the parse method): ...或直接使用日期字符串(即代表parse方法接受的日期的字符串):

new Date("2013/06/04");

...or by specifying the different parts of your date, like: ...或通过指定日期的不同部分,例如:

new Date(year, month, day [, hour, minute, second, millisecond]);

Take a look at this . 看看这个

您必须将13设置为2013,否则将默认使用1913

alert(new Date('04/06/2013'));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM