Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: how to parse a date string

The format is: MMDDHHMM

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

like image 601
Bin Chen Avatar asked Jan 13 '11 12:01

Bin Chen


People also ask

How do you convert a string to a Date in JavaScript?

You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.

How convert dd mm yyyy string to Date in JavaScript?

To convert a dd/mm/yyyy string to a date:Split the string on each forward slash to get the day, month and year. Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.

What is Date parse?

Date.parse() The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).


1 Answers

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));
like image 179
Thai Avatar answered Oct 14 '22 12:10

Thai