简体   繁体   中英

How to convert string to date format

I have string format data like below

Dec 26, 2014, 09:56 ET
Dec 31, 2014, 21:30 ET
Dec 30, 2014, 13:36 ET

And i want output in the below date format

26-12-2014 09:56:00
31-12-2014 21:30:00
30-12-2014 13:36:00

I have tried with the below code but it is giving different values. Correct me which syntax i can apply to convert string to date

str2date(input,"MMM dd, YYYY, HH:mm 'ET'")

You can try this if you don't want to use external libraries

 <html> <head> <script type="text/javascript"> function addZero(i) { if (i < 10) { i = "0" + i; } return i; } function myDate () { var dateValue = new Date("Dec 26, 2014, 09:56"); var d = dateValue.getDate(); var m = dateValue.getMonth(); var y = dateValue.getFullYear(); var h = addZero(dateValue.getHours()); var mi = addZero(dateValue.getMinutes()); var s = addZero(dateValue.getSeconds()); var newDate = (d + '-' + m + '-' + y + ' ' + h + ':' + mi + ':' +s); document.write(newDate); } </script> </head> <body> <script> myDate(); </script> </body> </html> 

Using a library is your best bet. The following is an example using MomentJS ;

 var input = [ 'Dec 26, 2014, 09:56 ET', 'Dec 31, 2014, 21:30 ET', 'Dec 30, 2014, 13:36 ET' ]; var output = input.map(function(dateString) { return moment(dateString, "MMM DD, YYYY, HH:mm ZZ").format('DD-MM-YYYY HH:mm:ss'); }); console.log(JSON.stringify(output, undefined, ' ')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.4/moment.min.js"></script> 

Output:

[
  "26-12-2014 04:56:00",
  "31-12-2014 16:30:00",
  "30-12-2014 08:36:00"
]

Hi You can easily implement this using Moment.js

 <html> <head> <script src="http://momentjs.com/downloads/moment.min.js"></script> </head> <body> <script> var inputDate = 'Dec 26, 2014, 09:56:00'; var formatString = 'DD-MM-YYYY hh:mm:ss'; var outputDate = moment(inputDate).format(formatString); document.write(outputDate); </script> </body> </html> 

 <script> function strDate(str){ var m = str.match(/(\\w+) (\\d{1,2}), (\\d{4}), (\\d{1,2}):(\\d{1,2})/); var month = []; month['Jan'] = 1; month['Feb'] = 2; month['Mar'] = 3; month['Apr'] = 4; month['May'] = 5; month['Jun'] = 6; month['Jul'] = 7; month['Aug'] = 8; month['Sep'] = 9; month['Oct'] = 10; month['Nov'] = 11; month['Dec'] = 12; return (m[2] + '-' + month[m[1]] + '-' + m[3] + ' ' + m[4] + ':' + m[5] + ':00'); } alert(strDate("Dec 26, 2014, 09:56 ET")); </script> 

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