How to convert 12-Jan-2016 like date string in javascript to 2016-01-12 00:00:00

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

How to convert 12-Jan-2016 like date string in javascript to 2016-01-12 00:00:00,

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 ?

回答1:

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

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


回答2:

You can use moment parsing function and format method:

var dateString = "12-Jan-2016"; var convertedFormat = moment(dateString, "DD-MMM-YYYY").format("YYYY-MM-DD HH:mm:ss"); console.log(convertedFormat); // this will display: 2016-01-12 00:00:00 

Please be sure that Jan is a valid month in your locale.



回答3:

I think this function might give you what you are searching for.

 def parseStringDate(String date,Boolean flagTime=false){     def date     def Format='yyyy-MM-dd'     def datePart=_date.toString().substring(0,10)     if (flagTime){         date = datePart+" "+_date.toString().substring(11,19)       Format=Format+" "+'HH:mm:ss'     }else date = datePart     return [date, Format] } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!