Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time using Moment JS

Tags:

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?

like image 653
fatCop Avatar asked Apr 05 '15 06:04

fatCop


People also ask

How do you find time from moment?

The moment(). hour() Method is used to get the hours from the current time or to set the hours.

What is Moment () in JavaScript?

Moment JS allows displaying of date as per localization and in human readable format. You can use MomentJS inside a browser using the script method. It is also available with Node. js and can be installed using npm.

What will Moment () return?

Moment. js helps display date with specified formats. moment() returns a date and format() converts the date string tokens and replaces them with specified format values, which are readable.

How can I get AM PM in moment?

To get am pm from the date time string using moment. js and JavaScript, we use the 'A' format code. console. log( moment("Mon 03-Jul-2022, 11:00 AM", "ddd DD-MMM-YYYY, hh:mm A").


1 Answers

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" 
like image 141
ThisClark Avatar answered Nov 05 '22 09:11

ThisClark