我有两次日历。
Calendar orarioP1 = new GregorianCalendar(2014, 3, 28, 8, 30, 00);
Calendar orarioA1 = new GregorianCalendar(2014, 3, 28, 12, 35, 06);
我实现了这个功能以获得时差,但它返回了我+ 1小时的差异
我需要返回正确的差异4:05:06
,但现在它返回5:05:06
。任何人都可以帮助我吗?
public String getTimeDiff() {
SimpleDateFormat sdf = new SimpleDateFormat("h:mm:ss");
long milliSec1 = orarioP1.getTimeInMillis();
long milliSec2 = orarioA1.getTimeInMillis();
long timeDifInMilliSec;
if(milliSec1 >= milliSec2) {
timeDifInMilliSec = milliSec1 - milliSec2;
} else {
timeDifInMilliSec = milliSec2 - milliSec1;
}
long timeDifSeconds = timeDifInMilliSec / 1000;
long timeDifMinutes = timeDifInMilliSec / (60 * 1000);
long timeDifHours = timeDifInMilliSec / (60 * 60 * 1000);
long timeDifDays = timeDifInMilliSec / (24 * 60 * 60 * 1000);
Date date = new Date(timeDifSeconds);
String difference = sdf.format(date);
return difference;
}
答案 0 :(得分:0)
你需要一个日期1970-01-01 04:05:06 GMT它会转移到你当前的时区。在您自己的矿石上格式化时间差可以更好地使用Joda Time库。
使用Joda Time的Period
课程。 Docs here
您的代码:
public String getTimeDiff() {
DateTime start = new DateTime(2014, 3, 28, 8, 30, 00);
DateTime end = new DateTime(2014, 3, 28, 12, 35, 06);
Period period = new Period(start, end);
return PeriodFormat.getDefault().print(period);
}
返回:4 hours, 5 minutes and 6 seconds
答案 1 :(得分:0)
你误解了它。
new Date(long timemillisec)
将返回since January 1, 1970, 00:00:00 GMT + your timemillisec
的日期实例
这是您的时区,使January 1, 1970, 00:00:00
略微接近January 1, 1970, 05:~:~
只需使用:
String difference = sdf.format(new Date(0));
您将获得相同的结果,即您的情况下1小时的差异,这是由于与GMT的时差。
看看你的代码,你将毫秒转换为秒,你不需要它。
只需使用millisecs:Date date = new Date(timeDifInMilliSec);
看看这个:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MMM/dd h:mm:ss");
System.out.println(sdf.format(new Date(0)));
System.out.println(sdf.format(new Date(1000)));
<强>输出强>
1970/Jan/01 5:30:00
1970/Jan/01 5:30:01
这是我的位置。
答案 2 :(得分:0)
尝试这样的事情
Calendar orarioP1 = new GregorianCalendar(2014, 3, 28, 8, 30, 00);
orarioP1.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar orarioA1 = new GregorianCalendar(2014, 3, 28, 12, 35, 06);
orarioA1.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Difference In Hours : "
+(orarioA1.get(Calendar.HOUR_OF_DAY)-orarioP1.get(Calendar.HOUR_OF_DAY)));
System.out.println("Difference In Minutes : "
+(orarioA1.get(Calendar.MINUTE)-orarioP1.get(Calendar.MINUTE)));
System.out.println("Difference In Seconds : "
+(orarioA1.get(Calendar.SECOND)-orarioP1.get(Calendar.SECOND)));
System.out.println("Difference In MiliSeconds : "
+(orarioA1.get(Calendar.MILLISECOND)-orarioP1.get(Calendar.MILLISECOND)));