我正在开发Android应用程序,我从服务器获取日期,例如:Thu Jul 02 14:18:58 GMT+04:00 2015
,在通过SimpleDateFormat解析它之后我得到它: 2015 年 7 月 2 日星期四下午 02:18。通过 Calender.getTime()
我得到了时间 Thu Jul 02 14:57:25 GMT+04:00 2015
解析它后我得到了 2015 年 7 月 2 日星期四下午 02:57
。现在我只需要计算两个日期和时间之间的时差。我正在做以下事情,但它给了我 NumberFormat 异常。请在这里帮助我。
Calendar cal = Calendar.getInstance();
cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE , MMMM dd , yyyy hh:mm a");
String systemTime = sdf.format(cal.getTime());
int lastLocationSyncInt = Integer.parseInt(lastLocationSync);
int systemTimeInt = Integer.parseInt(systemTime);
int lastSeenTimeDifference = systemTimeInt -lastLocationSyncInt ;
mMap.addMarker(markerOptions).setSnippet(lastSeenTimeDifference+"");
最佳答案
不要转换为整数,而是按日期格式并获取差异,如下所示
long days = 0;
long hours = 0;
SimpleDateFormat sourceFormat = new SimpleDateFormat(
"EEEE , MMMM dd , yyyy hh:mm a");
Date sDate = null;
Date sEdate = null;
try {
sDate = sourceFormat.parse(startdate);
sEdate = sourceFormat.parse(enddate);
long diff = sDate.getTime() - sEdate.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
hours = minutes / 60;
days = hours / 24;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如有任何疑问,请随时发表评论
关于java - 服务器时间和系统时间android的时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31182754/