Comparing date part only without comparing time in JavaScript

后端 未结 22 1842
春和景丽
春和景丽 2020-11-22 10:59

What is wrong with the code below?

Maybe it would be simpler to just compare date and not time. I am not sure how to do this either, and I searched, but I couldn\'t

22条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 11:48

    If you are truly comparing date only with no time component, another solution that may feel wrong but works and avoids all Date() time and timezone headaches is to compare the ISO string date directly using string comparison:

    > "2019-04-22" <= "2019-04-23"
    true
    > "2019-04-22" <= "2019-04-22"
    true
    > "2019-04-22" <= "2019-04-21"
    false
    > "2019-04-22" === "2019-04-22"
    true
    

    You can get the current date (UTC date, not neccesarily the user's local date) using:

    > new Date().toISOString().split("T")[0]
    "2019-04-22"
    

    My argument in favor of it is programmer simplicity -- you're much less likely to botch this than trying to handle datetimes and offsets correctly, probably at the cost of speed (I haven't compared performance)

提交回复
热议问题