0

I use DateTime in MySQL. So I have something like 2014-10-31 00:00:00 in my database.

From my API, when I return some query, I would normally have to loop through them and convert the DateTime to Timestamp using strtotime(). Then in JavaScript, I can use it by multiplying this timestamp by a 1000.

However, is there a way I could pass the pure DateTime to Javascript and do all the conversion there?

3
  • 1) You could also let MySQL do the conversion 2) Take a look at XDate.js, which provides date string into date object parsing. Commented Oct 30, 2014 at 22:51
  • I don't want to use an entire library for only a simple conversion! Is the conversation actually this complicated? Commented Oct 30, 2014 at 22:56
  • @Kousha Spend any time working with computers and time math and you'll find it's far more complicated than it seems. As an example, from 1909 to 1937 the Netherlands was exactly 19 minutes and 32.13 seconds ahead of UTC by law. Commented Oct 30, 2014 at 22:59

1 Answer 1

4

You can make MySQL do the work:

SELECT (UNIX_TIMESTAMP(date_field) * 1000) AS jsTimestamp FROM table;

Alternatively, Moment is pretty much the gold standard for JavaScript date work and can read MySQL-style strings right out of the box.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there a way to do this in JS?
@Kousha I linked you to Moment, a JavaScript library.
Yes, but I only need to do a simple conversion. I don't want to use an entire library if I am only going to do one parsing.
If you don't want to use libraries that are meant to ease up your life as a programmer, help you achieve your task in a timely manner, help and enforce interoperability - why do you even bother with programming at all?
If you don't want a library, I'd use the MySQL approach. I'd also work on the irrational fear of libraries as a longer-term goal.
|

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.