MOHANRAJ G
MOHANRAJ G

Reputation: 75

How to compare two time values in all formats using js?

I need to compare two time values in string type. It may be in following format,

=6:12>7:12 => False

=6:12 PM >7:12 AM => True

= 4/19/2017 6:12 PM > 4/19/2017 7:12 AM => True

like excel.

Can you please suggest me, how to achieve my scenario using JS

Upvotes: 0

Views: 591

Answers (2)

synthet1c
synthet1c

Reputation: 6282

Javascript has no native way to handle time's so you would need to make your own function to convert the timestamp into a unit that can be compared, in this instance I used seconds, but you could use milliseconds.

You have also shown a date stamp, which you can use the Date object to convert the timestamp into milliseconds which can be compared.

const timeToSeconds = s => {
  const m = s.match(/(\d{1,2})\:(\d{2})\s*(AM|PM)*/)
  return (
    (parseInt(m[1]) * 60) + 
    (parseInt(m[2])) + 
    (m[3] === 'PM' ? 12 * 60 : 0)
  )
}

console.log(
  timeToSeconds('6:12') > timeToSeconds('7:12')
)

console.log(
  timeToSeconds('6:12 PM') > timeToSeconds('7:12 AM')
)

console.log(
  new Date('4/19/2017 6:12 PM').getTime() > new Date('4/19/2017 7:12 PM').getTime()
)

Upvotes: 1

Rodrigo5244
Rodrigo5244

Reputation: 5535

Convert the dates to timestamps, then you can compare them using the > operator.

Upvotes: 0

Related Questions