如何将JavaScript中的日期字符串转换为2016年1月12日00:00:00 [英] How to convert 12-Jan-2016 like date string in javascript to 2016-01-12 00:00:00
本文介绍了如何将JavaScript中的日期字符串转换为2016年1月12日00:00:00的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将JavaScript的JavaScript日期字符串转换为2010年1月12日00:00:00,
How to convert 12-Jan-2016 like date string in javascript to 2016-01-12 00:00:00,
我正在看js似乎没有选项,而且我也尝试过js日期功能,但是正在返回无效的日期。
I am looking at moment js but there seems no options like and also I tried js date function but is is returning invalid date.
任何想法我在这里缺少什么?
Any idea what i am missing here ?
推荐答案
如果您只是尝试重新格式化字符串,那么不要打扰日期:
If you are just trying to reformat the string, then don't bother with dates:
function reformatDateString(ds) {
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
var b = ds.split('-');
return b[2] + '-' + months[b[1].toLowerCase()] + '-' + b[0] + ' 00:00:00';
}
document.write(reformatDateString('12-Jan-2016'));
然而,如果你真的需要将字符串解析为Date,然后执行此操作并分别格式化:
However, if you actually need to parse the string to a Date, then do that and format the string separately:
function parseDMMMY(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var b = s.split(/-/);
return new Date(b[2], months[b[1].toLowerCase()], b[0]);
}
document.write(parseDMMMY('16-Jan-2016'));
function formatDate(d) {
function z(n){return ('0'+n).slice(-2)}
return z(d.getDate()) + '-' + z(d.getMonth()+1) + '-' + d.getFullYear() +
' ' + z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
document.write('<br>' + formatDate(parseDMMMY('16-Jan-2016')));
这篇关于如何将JavaScript中的日期字符串转换为2016年1月12日00:00:00的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文