计算android中的时差

时间:2013-08-28 06:14:15

标签: java android

我有两次

String Time1= "13-08-2013 05:57:00 PM"
String Time2= "14-08-2013 06:00:00 AM"

请帮助计算android中两次之间的时差。

2 个答案:

答案 0 :(得分:8)

希望这会对你有所帮助

String Time1 = "10/02/14 09:29:50";
        String Time2 = "11/04/14 09:12:43";

            // date format
            SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss");  

        Date d1 = null;
        Date d2 = null;
        try {
            d1 = format.parse(Time1);
            d2 = format.parse(Time2);
        } catch (ParseException e) {
            e.printStackTrace();
        }    


        long diff = d2.getTime() - d1.getTime();
        long diffSeconds = diff / 1000;         
        long diffMinutes = diff / (60 * 1000);         
        long diffHours = diff / (60 * 60 * 1000);                      
        System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
        System.out.println("Time in minutes: " + diffMinutes + " minutes.");         
        System.out.println("Time in hours: " + diffHours + " hours."); 

答案 1 :(得分:1)

将字符串转换为日期,如下所示

String string = "01-01-2013 12:11:01";
Date date = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss", Locale.ENGLISH).parse(string);

然后您可以计算时间差异,如下所示

long diff= date2.getTime() - date1.getTime(); 
days = (int) (diff / (1000*60*60*24));  
hours = (int) ((diff - (1000*60*60*24*days)) / (1000*60*60)); 
min = (int) (diff - (1000*60*60*24*days) - (1000*60*60*hours)) / (1000*60);