Django
Django

Reputation: 363

Parsing JSON - Converting a Mongoose time stamp into EPOCH time

When I query my REST API, I get a JSON response like this:

{"litres":50,"nodeID":"2","location":"TESTDEPLOY","_id":"571645da91de00136612811b","__v":0,"time":"2016-04-19T14:51:06.489Z"}

Part of this response is the time stamp : "time":"2016-04-19T14:51:06.489Z"

Is there any way I can change this time stamp into Epoch time while parsing the JSON, as I want to feed it into a charting tool that uses EPOCH time.

Upvotes: 0

Views: 681

Answers (2)

clay
clay

Reputation: 6017

Check out MomentJS You would use this library to convert the time value after you received the response.

Something like:

var moment = require('moment');

//later in code
responseValue.time = moment(responseValue.time).valueOf(); //to get a value like 1415806206570

moment(String) creates a new "moment object" that parses the given value. .valueOf() give the time in milliseconds since the unix epoch.

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

Using momentJS you may convert the time field like:

var inputJson = {"litres":50,"nodeID":"2","location":"TESTDEPLOY","_id":"571645da91de00136612811b","__v":0,"time":"2016-04-19T14:51:06.489Z"};

var m = moment(inputJson.time, 'YYYY-MM-DDTHH:mm:ss.SSSZZ');

var ts = moment(inputJson.time).valueOf();

var s = m.format("M/D/YYYY H:mm");

document.write('ts: ' + ts + '  s: ' + s);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Upvotes: 1

Related Questions