compare dates in String format

后端 未结 10 1327
时光说笑
时光说笑 2021-02-12 16:30

I\'m getting two dates as String values and I wanted to check start time is earlier than the end time. I compare them as it is without converting them to date using Simple

10条回答
  •  梦如初夏
    2021-02-12 17:06

    My dates are coming from a string-based source and are always formatted YYYY-MM-DD, without time zone info or other complications. So when comparing a long list of dates, it's simpler and more efficient to compare them as strings rather than to convert them to date objects first.

    This was never a problem until I made this mistake in my code:

    boolean past = (dateStart.compareTo(now) == -1);
    

    This was giving some incorrect results because compareTo doesn't only return values as -1, 0 or 1. This was the simple fix:

    boolean past = (dateStart.compareTo(now) < 0);
    

    I'm including this gotcha here because this is one of the SO questions I found when trying to figure out what I was doing wrong.

提交回复
热议问题