【问题标题】:How to show date and time from milliseconds in Android?如何在 Android 中以毫秒为单位显示日期和时间?
【发布时间】:2013-01-05 17:14:56
【问题描述】:

我想显示旅行的日期。在应用程序中列出了几个行程,每个行程都有一个很长的值,其中包含其一代的 currentTimeMillis。我想把这个 long 数字变成一个日期,但输出总是在 1970 年左右...... System.currentTimeMillis() 是存储行程生成时间的正确方法吗?

Date date = new Date(trip.getStartTime());  // 195342322
SimpleDateFormat test = new SimpleDateFormat("yyyy-MM-dd"); 
startTime.setText(String.valueOf(test.format(date)));

-> startTime 的输出:1970-01-01

【问题讨论】:

  • 您的行程开始时间似乎在某处被截断。 195342322 毫秒是 1970-01-03。 195342322 是正确日期的非常小的值,今天的毫秒值是 1357406971942
  • 您是否有机会在内部从 long 转换为 int 然后再转换回 long?

标签: java android time milliseconds


【解决方案1】:

尝试使用Calendar进行简单格式化

【讨论】:

    【解决方案2】:

    我们不知道trip.getStartTime() 是如何实现的,但是它返回了错误的值。 195342322 是格林威治标准时间 1976 年 3 月 10 日星期三 21:45:22(您可以查看 online

    由于唯一未弃用的 Date 构造函数接受 long 参数,我猜你使用了它。最好以数据库友好的方式存储日期(时间),例如 ISO 8601。请注意,如果您将其存储在客户端的 SQLite 数据库中,则 SQLite 没有 time 类型,并且您必须为此使用 text 字段。

    切换到文本表示进行序列化后,您将能够使用SimpleDateFormat.parse() 取回Date

    【讨论】:

      【解决方案3】:

      使用这样的东西:

      Calendar calendar=Calendar.getInstance();
      calendar.setTimeInMillis(trip.getStartTime());
      Date date =calendar.getTime ();
      

      如图here.

      【讨论】:

      • setTimeInMillis 返回void。您的date 将为空:(
      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 2019-12-09
      • 2013-05-07
      • 2021-05-25
      • 1970-01-01
      • 2011-05-31
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多