1

I'm writing a PHP/JavaScript automation tool. In that tool, it's important to save the time which time was run, so we can use it to create a Google Finance style of stock chart, which allows us to follow the performance pattern of those tests. The data coming in is basic: date, a DateTime and average, the average time for each test.

id    Date                  Average

351   2013-04-22 15:57:49   154.3
347   2013-04-22 13:58:54   157
344   2013-04-22 12:00:06   444.7
340   2013-04-22 10:01:30   445.3
333   2013-04-22 08:02:24   263 

The data come in as a JSON, after being queried from the MySQL database. However, the API I'm using requires data as:

[
  [1145836800000,440.50],
  [1145923200000,427.16],
  [1146009600000,425.97],
  [1146096000000,420.03],
  [1146182400000,417.94]
]

I'm using HighStock to produce such charts. How can I convert the Datetime strings to milliseconds in JavaScript? * I'm using PHP in the backend.

2
  • What backend are you using? PHP? Commented Apr 22, 2013 at 23:36
  • @Jonast92 I'm using PHP in the backend Commented Apr 22, 2013 at 23:36

2 Answers 2

2

I recommend to do the conversion in the back-end.

Fetch the timestamp from the database, and instead of returning the selected timestamp then you should simply convert the timestamp and return it inside of the JSON.

Most of server side programming languages support a function for the converting.

You can do it like this in PHP:

// selectedTimeStamp is of the form 'Y-m-d H:i:s'
$strTime = strtotime($selectedTimeStamp);

But if you really want to do it in the javascript..

d.getTime();

Where d is the selected timestamp.

Example:

// The selected timestamp, using a dummy value here.
var selected = "April 04, 2013 22:30:00"; 
var d = new Date(selected); 
var ms = d.getTime();

It's possible that you have to convert it to this format, but I think that the w3school can show you more.

You can read more on: http://w3schools.com/jS/js_obj_date.asp

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

2 Comments

Bro, I do that and I get NAN. Do a console.log(ms) and see the output
Try it with the edited format I posted. You might have to convert the time. But really, just do it in the backend :) much easier.
2

If you're looking to do this with JavaScript then try this:

var ms = new Date("2013-04-22 15:57:49").getTime();  // 1366660669000

enter image description here

2 Comments

Bro, I do that and I get NAN. Do a console.log(ms) and see the output.
@philippe not sure why it's not working for you. Updated answer with screenshot.

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.