0

Here I need to compare two times and have to check whether the current time is sameOrBefore the given time.

  var workingDayTime = '1900'
  var currentTime = moment().format("HH:mm")
  var endTime = moment(workingDayTime,"HHmm").format("HH:mm")

console.log(currentTime) // 08:21
console.log(endTime) // 19:00

Assume the value of workingDayTime is coming from API in the format of ``HHMM`. I have checked the moment docs. And used something like endTime.isSameOrAfter(currentTime).

But it is returning endTime.isSameOrAfter is not a function . I believe this is because the current time and endTime have formatted to string this is not a function anymore. Is there any way to achieve the functionality I am looking for. Please help me with your suggestion and feedback

SDK
  • 1,356
  • 3
  • 19
  • 44
  • 1
    Try convert in milliseconds and compare directly. https://stackoverflow.com/a/9640384/5755317 – mathan Jun 08 '21 at 02:59
  • Like you said, it because you convert the moment object in a string with format method. Remove all `.format(...)` and your code will work if you use `endTime.isSameOrAfter(currentTime)` – AlTheLazyMonkey Jun 08 '21 at 07:08

2 Answers2

3

Compare the moment objects without the string formatting:

const workingDayTime = '1900'
const currentMoment = moment()
const currentTime = currentMoment.format('HH:mm')
const endMoment = moment(workingDayTime,"HHmm")
const endTime = endMoment.format("HH:mm")

const msg = (endMoment.isSameOrAfter(currentMoment))
  ? 'after'
  : 'before'
console.log(`${endTime} is ${msg} ${currentTime}`)
Matt
  • 68,711
  • 7
  • 155
  • 158
2

Don't format dates before you compare them

import moment from "moment";

var workingDayTime = '1900'
var currentTime = moment()
var endTime = moment(workingDayTime,"HHmm")

console.log(endTime.isSameOrAfter(currentTime)) // true
David
  • 306
  • 4
  • 13