Java\Android 时间戳返回错误的小时值

标签 java android timestamp

出于某种原因,我只运行了几秒钟,但时钟已经有 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/

相关文章:

java.lang.NoClassDefFoundError : jdk/nashorn/api/scripting/ScriptUtils in osgi bundle

java - 禁用/启用 OAuth2,无需两个安全配置

java - gradle 构建因未知主机异常而失败

php - 什么是 Unix 时间戳以及为什么要使用它?

mysql - 当月、日、小时或分钟为 8 或 9 时,INSERT TIMESTAMP 或 DATETIME 失败

java - 在 java 中调用方法时出现 NullPointerException

java可转换枚举

android - 如果上下文相同,为什么在 Android 中制作 Toast 的位置很重要?

android - 使用任何IP和任何端口号android监听数据报套接字

javascript - JS时区转换