简体   繁体   中英

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

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?

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM