简体   繁体   English

Javascript将日期从短格式转换为长格式

[英]Javascript Convert Date from short format to Long format

I am using the following code: 我正在使用以下代码:

var date="May-02-2012";
var startDate = date; 
var tmp = startDate.split('-'); 
tmp.splice(1, 0, ','); 
var convertedStartDate = new Date(tmp.join(' ')); 
var month = convertedStartDate.getMonth() + 1 
var day = convertedStartDate.getDate(); 
var year = convertedStartDate.getFullYear(); 
var shortStartDate = ('0' + day).slice(-2) + "-" + ('0' + month).slice(-2) + "-" + ('0' + year).slice(-2); 
return(shortStartDate);

The code above allows my to convert May-02-2012 to 02-05-12 上面的代码允许我将2012年5月2日转换为2012年2月5日

however, I now need to convert it from 02-05-12 back to May-02-2012 但是,我现在需要将其从2012年2月5日转换回2012年5月2日

But I can't work it out.. 但是我无法解决..

如果您不介意使用某个库,我会发现该库可以很好地工作: http : //www.datejs.com/

我建议使用javascript日期格式

No too hard provided the format is as you specified. 只要格式符合您的指定,就不用太费力了。 The following doesn't do any testing so if the format is wrong, it might to awry. 以下内容未进行任何测试,因此如果格式错误,则可能会出错。 But so will any function if you give it the wrong format. 但是,如果您给它错误的格式,那么任何函数也将如此。

var s = '02-05-12';

function toWeirdDate(s) {
   var months = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' ');
   var bits = s.split('-');
   return months[--bits[1]] + '-' + bits[0] + '-20' + bits[2];
}

alert(toWeirdDate(s)); // May-02-2012

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

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