Home > other >  Check if an iso string date is same or before an hour using moment
Check if an iso string date is same or before an hour using moment

Time:09-28

I've a string date in ISO format and a string in format HH:mm. I want to know if the hour of the string ISO date is same or before the string in format HH:mm.

Example:

const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '07:30' // not UTC
-> result true

---

const isoDateString = '2021-09-28T07:30:00Z' // UTC
const hour = '08:30' // not UTC
-> result false

I'm using moment and this is my code:

const TIME_FORMAT = 'HH:mm'

const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'

const isHourSameOrBeforeIsoString = moment(
  moment(isoDateString).format(TIME_FORMAT),
).isSameOrBefore(moment(hour, TIME_FORMAT));
console.log(isHourSameOrBeforeIsoString)

It doesn't work. It returns false in both cases. Why?

CodePudding user response:

Use moment.utc() when constructing your iso date string because you should handle that as in UTC.

I also added TIME_FORMAT inside moment constructor of formatted iso date string.

const TIME_FORMAT = 'HH:mm'

const isoDateString = '2021-09-28T09:30:00Z'
const hour = '07:30'

const isHourSameOrBeforeIsoString = moment(
  moment.utc(isoDateString).format(TIME_FORMAT), TIME_FORMAT
).isSameOrBefore(moment(hour, TIME_FORMAT));

console.log(isHourSameOrBeforeIsoString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

CodePudding user response:

Here is a more reasonable way to check in my opinion:

The logic you had was correct, but the reason it is returning false is because your isoDateString is returning 8:30 and the hour you are comparing it to is 7:30, like Krzysztof mentioned in their comment, it could be a time zone issue:

var format = 'hh:mm'

// var time = moment() gives you current time. no format required.
var time = moment('2021-09-28T09:30:00Z',format),
  testTime = moment('07:30', format);

console.log(moment(time).format(format));
console.log(moment(testTime).format(format));
  
if (time.isSameOrBefore(testTime)) {

  console.log('is before')

} 
if(time.isSameOrAfter(testTime)){

  console.log('is after')

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" referrerpolicy="no-referrer"></script>

  • Related