简体   繁体   中英

How to get the timestamp of a specific previous/last time with Moment.js?

The following gives me the timestamp of the current date-time:

Source

moment().utc().valueOf()

Output

1626964579209 // 2021-07-22T14:36:19Z

How do I get the timestamp of the previous/last 07:00 AM (2021-07-22T07:00:00Z) and 11:00 PM (2021-07-21T23:00:00Z) date-times?

Notice that, in this situation, the last/previous 11:00 PM timestamp is from the previous day (2021-07-21).

I've tried playing around with Moment.js Durations and Subtract Time but without much success.

Here's a StackBlitz to play around: https://stackblitz.com/edit/typescript-ofcrjs

Thanks in advance!

You could do

 const currentDateTime = moment().utc(); console.log('Current date-time timestamp:', currentDateTime.valueOf()); console.log('Current date-time string:', currentDateTime.format()); // If the current date-time string is 2021-07-22T14:36:19Z // then the previous/last 07:00 AM string is 2021-07-22T07:00:00Z and the // previous/last 11:00 PM string is 2021-07-21T23:00:00Z (previous day) let last7amTimestamp = currentDateTime.clone().startOf('d').add(7, 'h'); // ??? if (last7amTimestamp.isAfter(currentDateTime)) { last7amTimestamp.subtract(1, 'd') } let last11pmTimestamp = currentDateTime.clone().startOf('d').add(23, 'h'); // ??? if (last11pmTimestamp.isAfter(currentDateTime)) { last11pmTimestamp.subtract(1, 'd') } console.log('Previous/last 07:00 AM timestamp:', last7amTimestamp); console.log('Previous/last 11:00 PM timestamp:', last11pmTimestamp);

Did you mean like this?

moment('7:00 AM', 'h:mm A').subtract(1,'days').utc().valueOf();
moment('11:00 PM', 'hh:mm A').subtract(1,'days').utc().valueOf();

Just get the time of today and subtract day by 1.

You can test the current UTC hour and if it's after the required hour, just set the UTC hour to the time. If it's before, set it to the hour on the previous day, ie hour - 24.

Eg a general function to get the previous specified hour UTC given a supplied date or default to the current date without moment.js is:

 // Get the previous hour UTC given a Date // Default date is current date function previousUTCHour(h, d = new Date()) { // Copy d so don't affect original d = new Date(+d); return d.setUTCHours(d.getUTCHours() < h ? h - 24 : h, 0, 0, 0); } // Example let d = new Date(); console.log('Currently : ' + d.toISOString()); [1, 7, 11, 18, 23].forEach( h => console.log('Previous ' + (''+h).padStart(2, '0') + ' ' + new Date(previousUTCHour(h)).toISOString()) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM