Javascript date and time string, which have their own format

I need to parse a date and time string in the format "2015-01-16 22:15:00". I want to parse this in a JavaScript Date Object. Any help on this?

I tried some jquery plugins, moment.js, date.js, xdate.js. Not lucky yet.

+8
javascript jquery momentjs datejs
source share
5 answers

With a .js moment, you can create a moment object using the String + Format constructor:

var momentDate = moment('2015-01-16 22:15:00', 'YYYY-MM-DD HH:mm:ss'); 

Then you can convert it to a Date JavaScript object using the toDate () method:

 var jsDate = momentDate.toDate(); 
+23
source share

Best solution, now I'm using date.js - https://code.google.com/p/datejs/

I have included a script in my html page as this is

 <script type="text/javascript" src="path/to/date.js"></script> 

Then I just parsed the date line "2015-01-16 22:15:00" indicating the format as

 var dateString = "2015-01-16 22:15:00"; var date = Date.parse(dateString, "yyyy-MM-dd HH:mm:ss"); 
+6
source share
 new Date("2015-01-16T22:15:00") 

See Date.parse () .

The string must be in ISO-8601 format. If you want to analyze other formats, use moment.js .

 moment("2015-01-16 22:15:00").toDate(); 
+2
source share

I tried using the guys moment.js. But since I had this error, "ReferenceError: the moment is not defined", I had to skip this now. I am currently using a temporary solution.

 function parseDate(dateString) { var dateTime = dateString.split(" "); var dateOnly = dateTime[0]; var timeOnly = dateTime[1]; var temp = dateOnly + "T" + timeOnly; return new Date(temp); } 
+1
source share

If you are sure that you are in the right format and don’t need error checking, you can analyze it manually using split (and optionally replace it). I needed to do something similar in my project (MM / DD / YYYY HH: mm: ss: sss) and changed my decision according to your format. Note the subtraction of 1 per month.

 var str = "2015-01-16 22:15:00"; //Replace dashes and spaces with : and then split on : var strDate = str.replace(/-/g,":").replace(/ /g,":").split(":"); var aDate = new Date(strDate[0], strDate[1]-1, strDate[2], strDate[3], strDate[4], strDate[5]) ; 
+1
source share

All Articles