出于某种原因,我只运行了几秒钟,但时钟已经有 2 个小时了。 以下是时间戳和代码的结果:
08-12 01:03:47.858: I/System.out(2856): 1344722627872
08-12 01:03:51.198: I/System.out(2856): 1344722631206
08-12 01:03:54.698: I/System.out(2856): 3334
08-12 01:03:54.758: I/System.out(2856): 02:00:03
public static String getDate(long milliSeconds, String dateFormat) {
DateFormat formatter = new SimpleDateFormat(dateFormat);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime()); }
这是调用的完整代码:
// Click Listener for Check In\Out Button
checkIn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Check Out
myVib.vibrate(10);
if (clicked == true) {
timeStampWhenOut = System.currentTimeMillis();
killcheck = true;
checkedStatus = "Check In";
checkIn.setText(checkedStatus);
long getShiftLength = ShiftLength(timeStampWhenIn,
timeStampWhenOut);
System.out.println(timeStampWhenOut);
System.out.println(getShiftLength);
System.out.println(getDate(getShiftLength, "hh:mm:ss"));
clicked = false;
wasShift = true;
// Check In
} else if (clicked == false) {
timeStampWhenIn = System.currentTimeMillis();
System.out.println(timeStampWhenIn);
checkedStatus = "Check Out";
checkIn.setText(checkedStatus);
killcheck = false;
clicked = true;
}
}
});
为什么时间不对?
最佳答案
假设 3334
是耗时,您将日历设置为自纪元以来的 3.334 秒(大约 1970 年 12 月 31 日格林尼治标准时间午夜)。然后您要格式化该日历。它告诉你,你的时区现在是凌晨 2 点加 3 秒,据此我猜测你的时区是 GMT+2。
不要使用 Calendar 和 SimpleDateFormatter 来记录已过去的时间 - 它不是适合这项工作的工具。请查看 Apache-Commons 中的 DurationFormatUtils。
关于Java\Android 时间戳返回错误的小时值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11918052/