How to compare a date - String in the custom format “dd.MM.yyyy, HH:mm:ss” with another one?

冷暖自知 提交于 2019-12-13 00:22:03

问题


I have to check 2 date Strings in the custom format "dd.MM.yyyy, HH:mm:ss" against each other. How can I get the older one?

For example :

String date1 = "05.02.2013, 13:38:14";
String date2 = "05.02.2013, 09:38:14";

Is there a way to get date2 with comparing?


回答1:


You already have the date format, use it with SimpleDateFormat and then compare the created Date objects.

See demo here. Sample code:

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;
}

Of course, the method above returns the oldest date string entered. You can changed it (see the comments) to return the Date object instead.




回答2:


I'll just give you a brief explanation of how you should proceed. You need to first parse those date strings into Date object. Use DateFormat#parse(String) for that. After you get the Date object out of those strings, you can compare those objects using Date#compareTo(Date) method.




回答3:


Calulations with date and time are always tricky and I strongly recommend to use appropiate classes for this, you might want to check Joda Time for this.

Their classes provide methods such as daysBetween that give you the result you want.

Of course you have to parse your String to give you an Object representing this date and time first.



来源:https://stackoverflow.com/questions/17643743/how-to-compare-a-date-string-in-the-custom-format-dd-mm-yyyy-hhmmss-with

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!