【问题标题】:Convert linux timestamp to android date将linux时间戳转换为android日期
【发布时间】:2014-09-25 16:03:56
【问题描述】:

我必须将 linux 时间戳转换为 android 日期。 我从服务器得到这个号码

1386889262

我写了一个小代码sn-p。

Date d = new Date(jsonProductData.getLong(MTIME));
SimpleDateFormat f = new SimpleDateFormat("dd.MM.yyyy");
.setTimeZone(TimeZone.getTimeZone("GMT"));
formatTime = f.format(d);

但它没有正确转换,这是我的结果

17.01.1970

编辑: 通常我必须在这里得到这个

12.12.2013

还有其他方法可以得到正确的日期???

【问题讨论】:

标签: java android date


【解决方案1】:

如果您的 UNIX 时间戳是 10 位数字,那么它不包括毫秒,所以首先 1386889262*1000 如果它是 13 位数字,那么它也包括毫秒,那么您不必将 unix 时间戳乘以 1000。 在 Kotlin 中我们可以使用这个函数:

val unix=1386889262*1000 /*if time stamp is of 10 digit*/
val dateFormat = SimpleDateFormat("dd-MM-yy HH:mm:ss");
val dt =  Date(unix);
textview.settext(dateFormat.format(dt))

【讨论】:

  • 1.不正确。 10 位数的值准确表示自纪元以来的 。 2. 更喜欢使用库方法进行时间转换——即使是从秒转换为毫秒这样简单的方法。并且永远不要使用SimpleDateFormat。那门课是个臭名昭著的麻烦制造者,而且早已过时。
  • 那么除了 SimpleDateFormat 我们应该使用什么?@OleV.V.
  • 感谢您的关注。今天建议(我认为大多数专业人士也这样做)使用java.time, the modern Java date and time API,如the answer by Basil Bourque。格式化类是DateTimeFormatter。简而言之:Instant.ofEpochSecond(1_386_889_262L) .atZone(ZoneId.of("Asia/Kolkata")) .format(DateTimeFormatter.ofPattern("dd-MM-yy HH:mm:ss")) 产生13-12-13 04:31:02。大多数(不是全部)与SimpleDateFormat 一起使用的格式模式也可以与DateTimeFormatter 一起使用。
  • 对我来说,我必须把它加倍。 unix = 1386889262 * 1000L
【解决方案2】:

UNIX 时间戳应该以毫秒为单位,因此将 Long 值乘以 1000。所以您的值 1386889262 将是 1386889262000:

【讨论】:

    【解决方案3】:

    tl;博士

    Instant.ofEpochSecond( 1386889262L )
           .atZone( ZoneId.of( "Pacific/Auckland" ) )
           .toLocalDate()
           .toString()
    

    java.time

    您似乎从 UTC 1970 年第一刻的纪元参考日期算起整秒数,即 1970-01-01T00:00:00Z。

    现代方法使用 java.time 类来取代与最早版本的 Java 捆绑在一起的麻烦的旧日期时间类。对于较旧的 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。

    Instant 表示 UTC 时间线上的一个点,分辨率为纳秒(最多九位小数)。

    Instant instant = Instant.ofEpochSecond( 1386889262L ) ; 
    

    要生成一个代表这一刻的字符串,请调用toString

    String output = instant.toString() ; 
    

    确定日期需要时区。对于任何给定的时刻,日期在全球范围内因区域而异。分配ZoneId 以获取ZonedDateTime 对象。

    ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    为您的目的提取仅日期值。

    LocalDate ld = zdt.toLocalDate() ;
    

    生成一个字符串。

    String output = ld.toString() ;
    

    对于字符串中的其他格式,请在 Stack Overflow 中搜索 DateTimeFormatter

    【讨论】:

      【解决方案4】:

      您的时间戳或纪元时间似乎以 sec“1386889262”为单位。你必须这样做:

      long date1 =  1386889262*1000;
      SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm");
      Date dt = new Date(date1);
      datedisplay.setText(dateFormat.format(dt));
      

      你也可以通过java获取时间戳

      新日期().getTime() ;

      它返回一个长值。

      【讨论】:

      • 本代码使用了麻烦的旧日期时间类,这些类现在是遗留的,应该避免使用。由 java.time 类取代。对于较旧的 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      • 2017-04-25
      • 2022-01-08
      相关资源
      最近更新 更多