两个日期之间的差异会返回错误的结果

时间:2014-04-09 10:27:54

标签: android datetime

试图在两个日期之间取得差异,但这里没有给我正确的结果是我正在尝试的代码

String str = result.toString();
Log.v("Server Date TIme", str);
String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
Log.v("Device Date TIme", currentDateTimeString)
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date1 = dateFormat.parse(str);
Date date2 = new Date();

long diffM = date2.getTime() - date1.getTime();
String s = String.valueOf(diffM);
Log.v("Difference in Minutes: ", s);

long  diffH = diffM/60;
s = String.valueOf(diffH);
Log.v("Difference in Hours: ", s);

long diffD = diffH/24;
s = String.valueOf(diffD);
Log.v("Difference in Days: ", s);

这里是Log

04-09 15:25:16.870: V/Server Date TIme(26287): 2014-04-09 15:22:52
04-09 15:25:16.875: V/Device Date TIme(26287): 9 Apr 2014 15:25:16
04-09 15:25:16.875: V/Difference in Minutes:(26287): 144882
04-09 15:25:16.875: V/Difference in Hours:(26287): 2414
04-09 15:25:16.875: V/Difference in Days:(26287): 100

1 个答案:

答案 0 :(得分:2)

Date.getTime()从开始时间开始返回一个长整数毫秒。所以你需要用1000来得到秒,再用60来得到分钟,依此类推。