The format is: MMDDHHMM
I want to take month, day, hour, minute individu开发者_开发技巧ally, how to do that?
var dateString = '13011948';
The length of the text is fixed and always at the same position. Then you can just use substr
to cut them into parts and use parseInt
to convert them to 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));
If you're guaranteed that it's always going to be in MMDDHHMM format, you could parse it with a simple regex.
var d = "01121201";
var m = /([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})/.exec(d);
console.log(m);
which would output
["01121201", "01", "12", "12", "01"]
But using the actual date functions is better if possible.
You could do something like the following to take the result of the regex match above to create a true Javascript Date 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]);
EDIT
The moment.js library found here looks amazing for this!
END EDIT
this should help...working with Dates
There are several method in javascript Date object which would get you those parameters
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
Check this
If you do not have date object you can parse it using
var curdate = Date.parse("Jan 1, 2010");
To parse date to your specific format refer this
精彩评论