【问题标题】:Convert Time Format into Millisecond Android [duplicate]将时间格式转换为毫秒 Android [重复]
【发布时间】:2014-04-22 22:52:36
【问题描述】:

我想将简单的时间格式转换为毫秒。我说时间 3:14 我想将其转换为毫秒。我有以下代码,但它给了我一个负值。

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date d = format.parse("3:14");
long time = time.getTime();

【问题讨论】:

  • 我复制了你写的代码,我得到了time == 8040000。不过我有一个问题,你想从哪个日期开始转换成毫秒?因为您正在创建的 d 对象是 1970 年 1 月 1 日 3:14,我相信您想要从同一天 00:00 开始的那个时间的毫秒数。对吗?
  • ya as lagunex 说你希望它是什么日期
  • 问这种问题的时候,把你提到的负数等实际值贴出来。
  • @user1602152 “毫秒”是什么意思?日期时间自 1970 年初以来的毫秒数?自午夜以来的毫秒数?
  • @lagunex 我想从当前日期转换毫秒数

标签: android time simpledateformat


【解决方案1】:

说明

我的猜测……您忽略了指定时区。因此,在将字符串解析为 Date 实例时应用了 JVM 的默认时区。日期具有日期和时间部分。如果没有日期部分,该类假定您的意思是 epochfirst moment of 1970 UTC。我敢打赌,您的默认时区比 UTC 晚了 3 个多小时。因此,当调整到您的时区时,结果是 1969 年的日期时间。这样的日期时间(发生在纪元之前)用负数表示。

经验教训

(A) Specify a time zone 而不是依赖隐式默认值。

(B) 避免使用臭名昭著的 java.util.Date 和 .Calendar 类。使用Joda-Time 库。

(C) 如果您只想使用时间而不是日期,请使用 Joda-Time LocalTime 类。

【讨论】:

    【解决方案2】:

    要获取自 1970-01-01 到当前日期的毫秒数,只需使用

    System.currentTimeMillis();
    

    如果要获取自午夜以来经过的毫秒数,则必须获取午夜的时间并将其减去当前时间。这是完整的示例。

    // current time
    Calendar today = Calendar.getInstance();
    
    // Set the hour to midnight up to the millisecond
    today.set(Calendar.HOUR_OF_DAY,0);
    today.set(Calendar.MINUTE,0);
    today.set(Calendar.SECOND,0);
    today.set(Calendar.MILLISECOND,0);
    
    // compute currenttime - midnight to obtain the milliseconds of today
    long milliseconds = System.currentTimeMillis()-today.getTimeInMillis();
    

    【讨论】:

      猜你喜欢
      • 2019-07-04
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      相关资源
      最近更新 更多