Moment JS Date and time to timestamp in moment.js

13,019

Solution 1

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())

Solution 2

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()

Solution 3

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.

Share:
13,019

Related videos on Youtube

Will
Author by

Will

https://jsfiddle.net/w0mcr5vh/4/

Updated on June 04, 2022

Comments

  • Will
    Will almost 2 years

    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'));
    
  • VincenzoC
    VincenzoC almost 6 years
    I suggest not to use new Date for this kind of input. While it works as the OP expects, it could be not trivial to understand for non-US developers. I think it's better to explicitly tell how to parse the input.