Javascript: how to parse a date string

Format: MMDDhhmm

I want to take a month, day, hour, minute individually, how to do it?

+7
source share
4 answers
var dateString = '13011948'; 

The text length is fixed and always in the same position. Then you can simply use substr to cut them into pieces and use parseInt to convert them to a number.

 var month = parseInt(dateString.substr(0, 2), 10), day = parseInt(dateString.substr(2, 2), 10), hour = parseInt(dateString.substr(4, 2), 10), minute = parseInt(dateString.substr(6, 2), 10); 

Or instead, put it in a single date object.

 var date = new Date(); date.setMonth (parseInt(dateString.substr(0, 2), 10) - 1); date.setDate (parseInt(dateString.substr(2, 2), 10)); date.setHours (parseInt(dateString.substr(4, 2), 10)); date.setMinutes (parseInt(dateString.substr(6, 2), 10)); 
+7
source

EDIT

The current.js library found here looks amazing for this!

End edit

this should help ... work with dates

+4
source

If you are guaranteed that it will always be in the MMDDHHMM format, you can parse it with a simple regular expression.

 var d = "01121201"; var m = /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/.exec(d); console.log(m); 

which outputs

 ["01121201", "01", "12", "12", "01"] 

But using actual date functions is better if possible.

You can do something like the following to get the regex match result above to create a true Date Javascript object:

 //The year will default to the current year var realDate = new Date(); realDate.setMonth(m[1]); realDate.setDate(m[2]); realDate.setHours(m[3]); realDate.setMinutes(m[4]); 
+3
source

There are several methods in javascript Date that would give you these options

 var curdate = new Date(); var mday = curdate.getDate(); //returns day of month var month = curdate.getMonth(); //returns month 0-11 var hours = curdate.getHours(); //returns hours 0-23 var minutes = curdate.getMinutes(); //returns minutes 0-59 

Mark this

If you do not have a date object, you can parse it with

 var curdate = Date.parse("Jan 1, 2010"); 

To parse the date in your specific format, refer to this

+2
source

All Articles