compare dates in String format

后端 未结 10 1329
时光说笑
时光说笑 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条回答
  • what about

      "999-01-01 00:00:00"
    
    "10000-01-01 00:00:00"
    
    0 讨论(0)
  • 2021-02-12 17:22

    your approach is good because yyyy-mm-dd hh:ii:ss can be compared as a string and get correct results, other date formats will fail

    another option is to read this stackoverflow question

    How to compare dates in Java?

    and you should simply parse your strings and create Date or Calendar objects, depends on what you want to do , below is something I find useful

    http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

    0 讨论(0)
  • 2021-02-12 17:29

    You can compare the date time without properly parsing it if and only if these 3 conditions are met:

    1. The date time are always in the same format:

      • Same number of fields
      • The fields must be purely numeric. (String comparison: Jan > April, Wed > Thu).
      • The sizes of the fields are fixed (0 padded if necessary). For example, no proper padding will result in 10:01 < 1:01 (: has larger ASCII code than digits).
      • The non-numeric parts (including separators) must be the same down to the spacing.
    2. The fields are ordered in descending order by the size of the unit (larger unit to the right, and smaller unit to the left). For example: YEAR-MONTH-DAY HOUR:MINUTE:SECOND.MILISECOND

    3. They must be in the same time zone. The time zone information, if present, should have the same presentation (SGT and UTC+8 are currently equivalent, but the String comparison won't know about this). Note that the above ambiguous condition "same time zone" is enough for comparing equal, but to compare larger/smaller, there must be no change in time zone happening between the 2 dates being compare.

    0 讨论(0)
  • 2021-02-12 17:29

    Java or not, you must first ask these questions:

    • Do you need to compare time or just days ?
    • Do you need to check TimeZone, or all users are in the same timezone (or you don't care)

    If you need to compare days, then string in 'YYYY-MM-dd' format are just perfect and efficient :

    '2018-01-23' < '2018-03-21'. Always, in any language.

    With time and no timezone, then storing time in database as 'YYYY-MM-dd HH:mm:ss' is also good.

    With Timezone, then you have to learn your platforms (code and database), and understand what utc is (good luck !).

    (Used under CC BY-NC 2.5 license from http://xkcd.com/1179/.)

    0 讨论(0)
提交回复
热议问题