如何在java / android中比较时间(在字符串中给定输入)?

时间:2011-02-26 09:30:21

标签: java android

我有两个用于以 hh:mm 格式存储时间的字符串。我想比较这两个字符串以了解哪个时间更长。这是最简单的方法?

3 个答案:

答案 0 :(得分:20)

使用SimpleDateFormat和Date类。后者实现Comparable,因此您应该能够使用.compareTo()方法进行实际比较。例如:

            String pattern = "HH:mm";
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            try {
                Date date1 = sdf.parse("19:28");
                Date date2 = sdf.parse("21:13");

                // Outputs -1 as date1 is before date2
                System.out.println(date1.compareTo(date2));

                // Outputs 1 as date1 is after date1
                System.out.println(date2.compareTo(date1));

                date2 = sdf.parse("19:28");         
                // Outputs 0 as the dates are now equal
                System.out.println(date1.compareTo(date2));

            } catch (ParseException e){
                // Exception handling goes here
            }

有关模式,请参阅SimpleDateFormat文档。

答案 1 :(得分:11)

好吧,如果他们实际 hh:mm(包括前导零和24小时格式),那么你可以按字典顺序比较它们(即使用String.compareTo(String))。这是可排序格式的好处:)

当然,这不会检查两个值是否都是有效时间。如果你需要这样做,你应该解析两次:检查长度,检查冒号,解析两个子串,并可能将小时数乘以60并将其加到总数的分钟数分钟数。然后你可以比较这两个总数。

编辑:正如评论中所提到的,如果你需要解析这些值,无论出于何种原因,我个人建议使用Joda Time(可能是一个缩减版本,给定移动设备自然而不是SimpleDateTimeFormatDate。 Joda Time是比内置API更好的日期和时间API。

答案 2 :(得分:2)

我之前已经在我的Android程序中为此编写了函数,我很乐意分享下面的源代码。

函数(稍后将使用“如何使用”代码解释):

public static void String setFormattedTimeString(final String formatExpr,
                                   final long timeStampInSeconds) {     
    final Date dateFromTimeStamp = new Date(timeStampInSeconds);        
    final SimpleDateFormat simpleformat = new SimpleDateFormat(formatExpr);
    final String formattedDateInString = simpleformat.format(dateFromTimeStamp);        
    return formattedDateInString;
}

public static void Calendar setCalendar(final int year, final int month,
                                    final int day) {            
    final Calendar calendar = Calendar.getInstance();           
    calendar.set(Calendar.DAY_OF_MONTH, day);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.YEAR, year);
    return calendar;            
}

public static void double timeDifferenceInDays(final Calendar firstDate,
                                     final Calendar secondDate) {
    final long firstDateMilli = firstDate.getTimeInMillis();
    final long secondDateMilli = secondDate.getTimeInMillis();
    final long diff = firstDateMilli - secondDateMilli;   

    // 24 * 60 * 60 * 1000 because I want the difference in days. Change
    // as your wish. 
    final double diffDays = (double) diff / (double) (24 * 60 * 60 * 1000);

    return diffDays;
}

这就是我用它们计算差异的方法(本例中的天数)。在这个例子中,我假设你有一个时间戳,否则你可以轻松改变:

// Here you maybe have a timestamp in seconds or something..    

// This is ONE Calendar.
final String yearString = MyToolClass.setFormattedTimeString("y", timestamp);
final int year = Integer.parseInt(yearString);                                                   
final String monthString = MyToolClass.setFormattedTimeString("M", timestamp);
final int month = Integer.parseInt(monthString);                                      
final String day_in_monthString = MyToolClass.setFormattedTimeString("d",
                                        timestamp);
final int day_of_month = Integer.parseInt(day_in_monthString);

final Calendar calendarOne = MyToolClass.setCalendar(year, month,
                                        day_of_month);   

// Same stuff for Calendar two.

// Calculate difference in days.
final double differenceInDays = MyToolClass.timeDifferenceInDays(calendarOne,
                                        calendarTwo);