2

Hey, just wondering how to convert an HH:MM string into a javascript Date object. I have tried new Date(string); and myDate.setTime() but to no avail.

A side question could be: How to convert a string in HH:MM into milliseconds from Jan 1, 1970.

Thanks for your help in advance.

2 Answers 2

9

How about something like:

//using timestr '10:33:21', could also be '10-33-21'
var dat = new Date, time = timestr.split(/\:|\-/g);
dat.setHours(time[0]);
dat.setMinutes(time[1]);
Sign up to request clarification or add additional context in comments.

3 Comments

In my opinion, this is too "manual". There are parsing methods that can do the work.
As always [in javascript], there are many roads leading to Rome. This is one of them. I think it's usefull to know what one is doing before switching to more abstracted frameworks or libraries. It's a matter of taste I suppose.
what about AM/PM?
4

in JavaScript, I'm using the datejs library. http://www.datejs.com/ If you include this library, you have a function called "parseExact" and you could use it like this:

var dateString = "10-12";
var date = new Date.parseExact(dateString, "hh-mm");

To get the miliseconds, you can download the file time.js from http://code.google.com/p/datejs/source/browse/trunk/#trunk/src. Then you have a function getTotalMilliseconds() you can use:

var mSeconds = date.getTotalMilliseconds();

I hope this will help a little bit.

3 Comments

Hey, thanks for the quick reply. Sorry I can't vote you up yet (limit reached) but I now realise that my question was wrong, I meant HH:MM. If your answer still works for it, well then I'm happy.
This function parses any datetime-string. View some examples here: datejs.com/test/parseExact/index.html. And this functions also parses Date.parseExact(dateString, "HH-MM"). In my option it is more safety and elegant to use a parser-method instead of doing it manual.
P.S. This helps a lot. And thanks for the very comprehensive answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.