How to compare a date - String in the custom forma

2019-08-10 19:29发布

问题:

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.



标签: java date format