我正在尝试获取两个不同时区之间的时差,并在我的应用中进行某种同步。但是,我遇到了一个奇怪的问题。我得到的时差是错误的。任何帮助,将不胜感激。
if(msg.what == 101)
{
Log.v("today", server_date);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss aa"); //format for string to date conversion
Date date = null; //string to date convert
try {
date = (Date)formatter.parse(server_date);
} catch (ParseException e) {
e.printStackTrace();
}
long oldtime = date.getTime(); //date to milliseconds base 1970-01-01
Calendar nowdate = Calendar.getInstance(); //pick present time
String now_date = nowdate.toString();
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss aa");
String currentDateandTime = sdf2.format(new Date());
Log.v("today", currentDateandTime);
Date date1 = null;
try {
date1 = (Date)formatter.parse(currentDateandTime);
} catch (ParseException e) {
e.printStackTrace();
}
long nowtime = date1.getTime(); //convert to milli seconds
long timediff = nowtime - oldtime; //find difference
long hours, mins, secs;
hours = timediff/ (1000 * 60 * 60);
mins = (timediff - (hours * 1000 * 60 * 60)) / (1000 * 60);
secs = (timediff - (hours * 1000 * 60 * 60) - (mins * 60 * 1000))/ (1000);
Log.v("today", String.valueOf(timediff));
Log.v("today", String.valueOf(hours) + " hours " + String.valueOf(mins) + " mins " + String.valueOf(secs) + "secs");
}
下面是logcat:
11-12 13:20:13.732 32691-32691/com.example.sumit.myapplication V/today﹕ server_date: 2015-11-12 14:20:15 pm
11-12 13:20:13.732 32691-32691/com.example.sumit.myapplication V/today﹕ phone_date: 2015-11-12 13:20:13 PM
11-12 13:20:13.732 32691-32691/com.example.sumit.myapplication V/today﹕ difference: -2000
11-12 13:20:13.732 32691-32691/com.example.sumit.myapplication V/today﹕ 0 hours 0 mins -2secs