nunoarruda
nunoarruda

Reputation: 2904

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!

Upvotes: 0

Views: 924

Answers (3)

RobG
RobG

Reputation: 147363

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, i.e. hour - 24.

E.g. 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())
);

Upvotes: 0

dave
dave

Reputation: 64657

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

Upvotes: 1

Văn Vi
Văn Vi

Reputation: 51

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.

Upvotes: 0

Related Questions