简体   繁体   中英

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

however, I now need to convert it from 02-05-12 back to May-02-2012

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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