Home > Javascript, mysql, PHP, Tips > Getting datetime type into JavaScript as Date object

Getting datetime type into JavaScript as Date object

March 25th, 2010 Leave a comment Go to comments

This is not any new thing and may be discussed at different other places. But just as I came across like any other things, I just wanted to make a record of this.

When selecting datetime to be displayed in a JavaScript ui library, select the unix_timestamp * 1000 from the sql.

In MySQL it is straight:

 SELECT unix_timestamp(now()) * 1000 as unix_utime
 
 +---------------+
 | unix_utime    |
 +---------------+
 | 1269483801000 | 
 +---------------+

In MsSQL you will need a bit juggling.

 select Convert(bigint, DateDiff(s, '1970-01-01 00:00:00', GetDate())) * 1000 as unix_utime
 
 +---------------+
 | unix_utime    |
 +---------------+
 | 1269504598000 | 
 +---------------+

Okay if it is PHP you have different ways to get the timestamp, just go ahead and multiply it by 1000. In case you are so accuracy freak, microtime(true) * 1000 would be even better, but that will give you accurate times for the current time only. Though it is fun when you use things like strtotime, to get the timestamp of a said date, or string representation. Just multiply this timestamp with 1000 and you will get the unix_utime (unix microtime).

Passing this to the JavaScript Date constructor like xtime = new Date(<unix_utime>) would get you the Date object in JavaScript.

Unix Micro Time, MsSQL unix_timestamp, JavaScript Date from MySQL datetime

Categories: Javascript, mysql, PHP, Tips Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

twelve − = eight