如何比较日期 - 自定义格式“dd.MM.yyyy,HH:mm:ss”中的字符串与另一个? [英] How to compare a date - String in the custom format "dd.MM.yyyy, HH:mm:ss" with another one?
本文介绍了如何比较日期 - 自定义格式“dd.MM.yyyy,HH:mm:ss”中的字符串与另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须以自定义格式dd.MM.yyyy,HH:mm:ss$查看2日期
String
c $ c>对方。
如何获得较旧的?
I have to check 2 date String
s in the custom format "dd.MM.yyyy, HH:mm:ss"
against each other.
How can I get the older one?
例如:
String date1 = "05.02.2013, 13:38:14";
String date2 = "05.02.2013, 09:38:14";
有没有办法获得 date2
比较?
推荐答案
您已经拥有日期格式,请使用 SimpleDateFormat
,然后比较创建的 日期
对象。
You already have the date format, use it with SimpleDateFormat
and then compare the created Date
objects.
请参阅演示。 a> 示例代码
public static void main(String[] args) Exception {
String date1 = "05.02.2013, 13:38:14";
String date2 = "05.02.2013, 09:38:14";
System.out.println(getOlder(date1, date2)); // 05.02.2013, 13:38:14
System.out.println(getOlder(date2, date1)); // 05.02.2013, 13:38:14
}
public static String getOlder(String one, String two) throws ParseException {
Date dateOne = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss").parse(one);
Date dateTwo = new SimpleDateFormat("dd.MM.yyyy, HH:mm:ss").parse(two);
if (dateOne.compareTo(dateTwo) > -1) {
return one; // or return dateOne;
}
return two; // or return dateTwo;
}
当然,上面的方法返回输入的最旧的日期字符串。您可以更改它(请参阅注释)以返回 Date
对象。
Of course, the method above returns the oldest date string entered. You can changed it (see the comments) to return the Date
object instead.
这篇关于如何比较日期 - 自定义格式“dd.MM.yyyy,HH:mm:ss”中的字符串与另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文