How to get time using Moment JS
Asked Answered
W

6

29

I've two javascript variables: startDate and endDate. I want to store the current time(unix timestamp in ms) to endDate and timestamp of 24 hours before in startDate. I'll use this two variables to query the records for last 1 day. How can I do that using moment JS?

Wilhelmstrasse answered 5/4, 2015 at 6:38 Comment(0)
D
25

Have you looked at the website yet? It's full of examples - http://momentjs.com/ I think what you are trying to do is as simple as

var startDate = moment(endDate).subtract(1, 'days');

Following your question more literally, you can do this:

var endDate = moment(); //the current time

Or, you can just ignore the endDate part of this problem and go straight to startDate with

var startDate = moment().subtract(1, 'days'); //one day before the current time

Finally, if you need to format it a certain way, you can apply a formatting rule such as:

moment().subtract(1,'days').format('YYYY-MM-DD h:mm:ss a')

Use format without an argument and it gives you ISO 8601 format

moment().subtract(1,'days').format() //eg: "2015-04-04T01:53:26-05:00"
Demoniac answered 5/4, 2015 at 6:41 Comment(1)
actually I've figured a workaround var startdate = moment.utc(moment().subtract(1, 'days').format("MM/DD/YYYY"), "MM/DD/YYYY").valueOf(); // to unix time stamp in ms var enddate = moment.utc(moment().format("MM/DD/YYYY"), "MM/DD/YYYY").add('d', 1).subtract('s', 1).valueOf(); // to unix time stamp in msWilhelmstrasse
P
17

This worked for me although I have never found it in the docs. Should have been published but it works.

Try:

moment(currentTime).format("hh:mm"));or 
var currentTime = moment();
    console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));
Penetralia answered 29/10, 2017 at 5:7 Comment(0)
R
13

For those who are looking for a way to get timestamp, just do it:

moment().valueOf()

Rend answered 26/10, 2020 at 1:27 Comment(0)
P
10

I think what you are looking for is something like

moment(endDate).unix()

which returns something like: 1435161240

You can even calculate the time from now using

moment(endDate).fromNow()

which returns something like: "2 days ago"

Polyzoic answered 26/6, 2015 at 5:16 Comment(0)
A
10

You can directly call function momentInstance.valueOf(), it will return numeric value of time similar to date.getTime() in native java script.

Altimeter answered 28/8, 2017 at 8:4 Comment(1)
for clarification: moment().valueOf() outputs exactly the same as new Date().getTime()Loginov
F
0

If you read the MomentJs documents (http://momentjs.com/docs/#/displaying/) you can find this format:

moment("2015-01-16T12:00:00").format("hh:mm:ss a")
Ferrule answered 4/5 at 12:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.