且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将JavaScript中的日期字符串转换为2016年1月12日00:00:00

更新时间:2022-11-22 12:54:41

如果您只是尝试重新格式化字符串,那么不要打扰日期:

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')));