java 比较字符串格式的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14125038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
compare dates in String format
提问by someone
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 SimpleDateFormat
, like this:
我得到两个日期作为字符串值,我想检查开始时间早于结束时间。我将它们按原样进行比较,而没有使用 将它们转换为日期SimpleDateFormat
,如下所示:
String startTime = "2013-01-02 14:25:56";
String endTime = "2013-01-02 14:30:56";
if(endTime.compareTo(startTime) > 0){
System.out.println("End time is greater than start time");
}
Is it really necessary to convert them to date and compare? Will I miss anything? Am I doing the right thing?
真的有必要将它们转换为日期并进行比较吗?我会想念什么吗?我在做正确的事吗?
采纳答案by stacker
Is it really necessary to convert them to date and compare?
真的有必要将它们转换为日期并进行比较吗?
If you don't have to include timezones and can ensure that you always have this format the lexical order will work.
如果您不必包含时区并且可以确保始终使用此格式,则词法顺序将起作用。
Will I miss anything?
我会想念什么吗?
You lose the flexibility
你失去了灵活性
Am I doing the right thing?
我在做正确的事吗?
That depends on the point of view. I use something similar in a specialized search-enginge (only for performance reasons). Usually I convert to Date and compare these objects.
这取决于观点。我在专门的搜索引擎中使用了类似的东西(仅出于性能原因)。通常我转换为 Date 并比较这些对象。
回答by Joachim Sauer
What you will be missing is the verification if the dates are in fact well-formatted.
如果日期实际上格式正确,您将缺少的是验证。
Ifthe dates are formatted exactlyas you showed every time, then this will work. If there's any chance that it might be different, then parsing and comparing the resulting Date
objects will add at least somewhat of a check.
如果日期的格式与您每次显示的完全一样,那么这将起作用。如果有可能不同,那么解析和比较结果Date
对象至少会增加一些检查。
For example if oneof the two dates happens to be formatted as 2013.01.02 14:30:56
or it even included an unformatted date such as yesterday
then your code would silently assume some order (that most likely has little to do with the actual order) and proceed. What it shoulddo is notify the user (or the log file, ...) that some expectation was not met.
例如,如果一个两个日期碰巧被格式化为2013.01.02 14:30:56
或者甚至包括一个未格式化的日期,例如yesterday
你的代码会默默地承担了部分的顺序(即最有可能有一点与实际为了做到),并继续进行。它应该做的是通知用户(或日志文件,...)某些期望没有得到满足。
回答by burna
It is not good practice and a code smell.
这不是一个好习惯和代码味道。
You lose semantic correct and readable code. (and extensibility, timezones, and the other right things, that already had been said)
您会丢失语义正确且可读的代码。(以及已经说过的可扩展性、时区和其他正确的事情)
You don't want to compare two String
s, you want to compare 2 Date
s - so just do this, compare two Date
objects.
您不想比较两个String
s,而是想比较 2 个Date
s - 所以就这样做,比较两个Date
对象。
If you create unit-tests and test your comparing method, you will never write a method that compares 2 "string"-dates correctly in every case, without converting them to dates.
如果您创建单元测试并测试您的比较方法,您将永远不会编写在每种情况下都正确比较 2 个“字符串”日期的方法,而不会将它们转换为日期。
回答by nhahtdh
You can compare the date time without properly parsing it if and only if these 3 conditions are met:
当且仅当满足以下 3 个条件时,您才能比较日期时间而无需正确解析它:
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.
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
They must be in the same time zone. The time zone information, if present, should have the same presentation (
SGT
andUTC+8
are currently equivalent, but the String comparison won't know about this). Note that the above ambiguouscondition "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.
日期时间总是采用相同的格式:
- 相同数量的字段
- 字段必须是纯数字。(字符串比较:
Jan
>April
,Wed
>Thu
)。 - 字段的大小是固定的(如有必要,填充 0)。例如,没有适当的填充将导致
10:01
<1:01
(:
ASCII 代码大于数字)。 - 非数字部分(包括分隔符)必须与空格相同。
字段按单位大小降序排列(右侧较大的单位,左侧较小的单位)。例如:
YEAR-MONTH-DAY HOUR:MINUTE:SECOND.MILISECOND
他们必须在同一时区。时区信息(如果存在)应该具有相同的表示形式(
SGT
并且UTC+8
当前是等效的,但字符串比较不会知道这一点)。请注意,上述不明确的条件“相同时区”足以比较相等,但要比较更大/更小,则要比较的 2 个日期之间的时区不得发生变化。
回答by irreputable
what about
关于什么
"999-01-01 00:00:00"
"10000-01-01 00:00:00"
回答by MrFox
Yes, it is better to convert the String to Date and compare.
是的,最好将字符串转换为日期并进行比较。
- It ensures they are actually valid dates so no 20-20-2012.
- Once the conversion is complete only a single number comparison remains.
- It allows for great flexibility when comparing dates of different formats.
- The alternative is writing code that parses each number and compares it to the other, which is just as much work.
- 它确保它们实际上是有效的日期,所以没有 20-20-2012。
- 转换完成后,只剩下一个数字比较。
- 它在比较不同格式的日期时提供了很大的灵活性。
- 另一种方法是编写代码来解析每个数字并将其与另一个进行比较,这同样需要很多工作。
回答by Scott Stafford
I would recommend converting them to date first to be a little safer, but as long as you are SURE the format (or timezone, etc...) will never change on you, then a date compare and comparing that format of string should always be equivalent.
我建议先将它们转换为日期更安全一些,但只要您确定格式(或时区等...)永远不会改变您,那么日期比较和比较该字符串格式应该始终是等价的。
回答by cristi _b
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
您的方法很好,因为 yyyy-mm-dd hh:ii:ss 可以作为字符串进行比较并获得正确的结果,其他日期格式将失败
another option is to read this stackoverflow question
另一种选择是阅读this stackoverflow question
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
你应该简单地解析你的字符串并创建 Date 或 Calendar 对象,这取决于你想要做什么,下面是我觉得有用的东西
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
回答by Nicolas Zozol
Java or not, you must first ask these questions:
Java与否,你必须先问这些问题:
- 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)
- 你需要比较时间还是只需要几天?
- 你需要检查TimeZone,还是所有用户都在同一个时区(或者你不在乎)
If you need to compare days, then string in 'YYYY-MM-dd' format are just perfect and efficient :
如果您需要比较天数,那么 'YYYY-MM-dd' 格式的字符串是完美而高效的:
'2018-01-23' < '2018-03-21'
. Always, in any language.
'2018-01-23' < '2018-03-21'
. 总是,以任何语言。
With time and no timezone, then storing time in database as 'YYYY-MM-dd HH:mm:ss' is also good.
有时间没有时区,然后将时间存储在数据库中为 'YYYY-MM-dd HH:mm:ss' 也不错。
With Timezone, then you have to learn your platforms (code and database), and understand what utc is (good luck !).
使用时区,那么您必须了解您的平台(代码和数据库),并了解 utc 是什么(祝您好运!)。
(Used under CC BY-NC 2.5 license from http://xkcd.com/1179/.)
(在来自http://xkcd.com/1179/ 的CC BY-NC 2.5 许可下使用。)
回答by arlomedia
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.
我的日期来自基于字符串的源,并且总是格式化为 YYYY-MM-DD,没有时区信息或其他复杂情况。因此,在比较一长串日期时,将它们作为字符串进行比较比先将它们转换为日期对象更简单、更有效。
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:
这给出了一些不正确的结果,因为 compareTo 不仅返回值 -1、0 或 1。这是简单的修复:
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.
我在这里包括这个问题,因为这是我在试图找出我做错了什么时发现的 SO 问题之一。