Defoe
Defoe

Reputation: 371

Converting Moment utc time into unix time

Hello guys I was wondering how do I convert a date into Unix time stamp using the library moment.js so I can compare the oldDate with another date.

This is what I tried:

var oldDate = (moment.unix(1490632174)).format();
// here I got the Date in string format
var newDate= moment.utc('2017-03-27T18:29:59+02:00', "YYYY-MM-DD");
// now I want to convert it again into unix timestamp and I don't know how to do it.
console.log(oldDate, newDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 4

Views: 12981

Answers (3)

quantum
quantum

Reputation: 11

Another way you could approach this is to leverage the native Date.parse("2017-03-27T18:29:59+02:00 GMT") method in Javascript. This method parses a date string and returns Unix Time in ms.

For more info, checkout Date.parse() documentation and this Unix Time Converter that makes use of both moment and the native JS method.

Upvotes: 1

gforce301
gforce301

Reputation: 2984

Documentation is a wonderful thing. Unix Timestamp (seconds)

moment().unix();

moment#unix outputs a Unix timestamp (the number of seconds since the Unix Epoch).

moment(1318874398806).unix(); // 1318874398

This value is floored to the nearest second, and does not include a milliseconds component.

var oldDate = moment.unix(1490632174).unix();
// here I got the Date in string format
var newDate= moment.utc('2017-03-27T18:29:59+02:00', "YYYY-MM-DD");
// now I want to convert it again into unix timestamp and I don't know how to do it.
console.log(oldDate, newDate.unix());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 6

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146660

You can use the < and > operators:

var oldDate = moment.unix(1490632174);
var newDate= moment.utc('2017-03-27T18:29:59+02:00', "YYYY-MM-DD");

console.log(oldDate<newDate, oldDate>newDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>

Upvotes: 2

Related Questions