Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can the Moment.js get the timestamp?

Tags:

javascript

How can I get the timestamp after manipulating days in Moment.js?

I tried use:

var a = moment().subtract(10, 'days').calendar().getTime()

to get the timestamp, but failed.

like image 999
qg_java_17137 Avatar asked Oct 18 '25 18:10

qg_java_17137


2 Answers

It is not really clear what you mean by "timestamp".

To get the number of milliseconds since the Unix epoch, use moment().valueOf();. This corresponds to JS Date.getTime();.

To get the number of seconds since the Unix epoch, use moment().unix();.

To get the hour/minute/second as numbers, use moment().hour(); / moment().minute(); / moment().second();.

To get the ISO 8601 string (recommended for sending data over the wire), use moment().toISOString(); (e.g. "2013-02-04T22:44:30.652Z").

To print a user readable time, use moment().format();, e.g. moment().format('LTS') will return the localized time including seconds ("8:30:25 PM" for en-Us).

See moment.js - Display - Format for format specifiers.

like image 170
Georg Patscheider Avatar answered Oct 20 '25 06:10

Georg Patscheider


Classic calendar formatting:

const daysBefore = moment().subtract(10, 'days').calendar();

for unix timestamp (current date minus 10 days):

const daysBefore = moment().subtract(10, 'days').unix();

Just remember, apply formatting after subtraction, as formatting returns a string, not momentjs object.

like image 37
justMe Avatar answered Oct 20 '25 06:10

justMe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!