简体   繁体   中英

How to compare two different dates which are in two different formats in javascript?

I am trying to compare two different time formats in JavaScript.

Day 1: Thu Dec 31 00:00:00 GMT 2020

Day 2: Today's date. I am using today=new Date(); which gives me Thu Sep 21 2017 11:42:17 GMT-0400 (Eastern Daylight Time)

I want to check if Day 1 is today or in future, basically if Day 1 >= Day 2. I am only looking for dates and not datetime. Any help is appreciated.

I think this should work

let myDate = Date.parse('Thu Dec 31 00:00:00 GMT 2020')
console.log('myDate:', myDate)

let today  = Date.parse(new Date())
console.log('Today:', today)

if (myDate >= today) {
  console.log("True")
} else {
  console.log("False")
}

If you use Date.parse() it breaks it down into (I believe) epoch time and makes them comparable. This works with a ton of different date formats.

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