比较Java中的日期字符串 [英] Comparing date strings in Java

查看:115
本文介绍了比较Java中的日期字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用 dateString1.compareTo(dateString2),它根据每个字符的Unicode值对字符串进行词典比较,并返回一个int。这是一个代码示例。

So I am using dateString1.compareTo(dateString2) which does a lexicographic comparison with strings, based on the Unicode value of each character, and returns an int. Here is a code sample.

String dateString1 = "05-12-2012";
String dateString2 = "05-13-2012";
if (dateString1.compareTo(dateString2) <=0){
   System.out.println("dateString1 is an earlier date than dateString2");
}

这是一个错误的方法来比较Java中的日期吗?

Is this a wrong approach to compare dates in Java?

在我的测试中,我没有遇到意外结果的情况。我真的不想在字符串中创建一个Date对象,如果我不需要,因为我在一个漫长的循环中这样做。

In my tests, I have not run into a situation where I have gotten unexpected result. I really do not want to create a Date object out of the string, if I don't have to, because I am doing this inside a long running loop.

忍者编辑
从下面的答案中清除,将日期作为字符串进行比较没有错误,如果它在 yyyyMMdd 格式,但如果它是任何其他格式,它显然会导致错误。

Ninja Edit Gleaning from the answers below there is nothing wrong with comparing dates as a string if it is in yyyyMMdd format but if it is in any other format it will obviously result in error.

我实际上有我的日期字符串为 yyyyMMdd 格式在我的实际代码。 (我在上面给出的例子中输入了错误的格式)所以现在,我将直接离开代码,并添加几行注释来证明我的决定。

I actually have my date string as yyyyMMdd format in my actual code. (I typed the format wrong in the example I gave above.) So for now, I will just leave the code as it is, and add few lines of comments to justify my decision.

但是我现在看到,比较这样的字符串是非常有限的,如果dba决定在路上更改日期格式,我将遇到错误,我不会看到发生。

But I now see that comparing strings like this is very limiting and I will run into bugs if dba decides to change the date format down the road, which I don't see happening.

推荐答案

我建议你做正确的事情(如下所述)并转换为正确的 Date 对象进行比较。担心性能影响,如果它实际影响到您的应用程序(它可能不会)。

I suggest you do the Right Thing (as described here) and convert to proper Date objects to compare. Worry about the performance impact if and when it actually impacts your application (which it probably won't).

这篇关于比较Java中的日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆