Will
Will

Reputation: 165

Moment JS Date and time to timestamp in moment.js

I am getting a text value and it is formatted like this : "9/19/2018 10:00 AM". How would you go about turning this into an epoch timestamp using moment.js or just javascript?

EXAMPLE:

console.log(moment('4/17/2018 10:00 AM', 'mm/dd/yyyy hh:mm a').format('x'));

Upvotes: 2

Views: 15503

Answers (3)

VincenzoC
VincenzoC

Reputation: 31502

The issue in your code is that you are using wrong tokens while parsing your input. Moment token are case sensitive and mm stands for 0..59 minutes, dd stands for day name (according locale) and there is no lowercase yyyy supported.

Use M for 1..12 month number, uppercase D or DD for day of month and uppercase YYYY for year as stated in moment(String, String) docs.

Your code could be like:

console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').format('x'));
console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

Note that you can use both format('x') (returns a String) and valueOf() (returns a Number).

I suggest to use moment(String, String) over new Date() (Date.parse()) because this way you explicitly state how to parse you input (what would you expect for input like 1/2/2018? 1st of February or January 2nd?). See here a note about Date.parse behaviour

Somewhat surprisingly, these formats (e.g. 7/2/2012 12:34) are also unambiguous. Date.parse favors US (MM/DD/YYYY) over non-US (DD/MM/YYYY) forms.

These formats may be ambiguous to humans, however, so you should prefer YYYY/MM/DD if possible.

Upvotes: 3

Shubhanu Sharma
Shubhanu Sharma

Reputation: 2132

normal js

new Date("9/19/2018 10:00 AM");

if you want to do with moment js

moment("9/19/2018 10:00 AM").unix()

Upvotes: 3

Ashish Ranjan
Ashish Ranjan

Reputation: 12970

Use the date string to create a date Object and then use getTime() method of the Object.

date = new Date("9/19/2018 10:00 AM");
console.log(date.getTime())

Upvotes: 4

Related Questions