【问题标题】:long timestamp to LocalDateTimeLocalDateTime 的长时间戳
【发布时间】:2017-12-06 14:18:31
【问题描述】:

我有一个长时间戳 1499070300(相当于 2017 年 7 月 3 日星期一 16:25:00 +0800),但是当我将其转换为 LocalDateTime 时,我得到 1970-01-18T16:24:30.300

这是我的代码

long test_timestamp = 1499070300;

LocalDateTime triggerTime =
                LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone
                        .getDefault().toZoneId());

【问题讨论】:

标签: java java-8 timestamp java-time


【解决方案1】:

您需要以毫秒为单位传递时间戳:

long test_timestamp = 1499070300000L;
LocalDateTime triggerTime =
        LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), 
                                TimeZone.getDefault().toZoneId());  

System.out.println(triggerTime);

结果:

2017-07-03T10:25

或者改用ofEpochSecond

long test_timestamp = 1499070300L;
LocalDateTime triggerTime =
       LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp),
                               TimeZone.getDefault().toZoneId());   

System.out.println(triggerTime);

结果:

2017-07-03T10:25

【讨论】:

  • 谢谢。我错过了
  • 顺便说一句,如果您使用的是 AndroidThreeTen,请将 TimeZone.getDefault().toZoneId() 替换为 DateTimeUtils.toZoneId(TimeZone.getDefault())
【解决方案2】:

试试下面的..

long test_timestamp = 1499070300000L;
    LocalDateTime triggerTime =
            LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp), TimeZone
                    .getDefault().toZoneId());  

默认情况下,1499070300000 如果结尾不包含 l,则为 int。也以毫秒为单位传递时间。

【讨论】:

    【解决方案3】:

    如果您使用的是 Android threeten back 端口,那么您想要的线路是这样的

    LocalDateTime.ofInstant(Instant.ofEpochMilli(startTime), ZoneId.systemDefault())
    

    【讨论】:

      【解决方案4】:

      尝试使用Instant.ofEpochMilli()Instant.ofEpochSecond() 方法-

      long test_timestamp = 1499070300L;
      LocalDateTime date =
          LocalDateTime.ofInstant(Instant.ofEpochMilli(test_timestamp ), TimeZone
              .getDefault().toZoneId());
      

      【讨论】:

      • 您的意思是“尝试使用 Instant.ofEpochSecond()”,对吗?否则你的文字会令人困惑。
      【解决方案5】:

      您的问题是时间戳不是以毫秒为单位,而是以从纪元日期开始的秒数表示。将时间戳乘以 1000 或使用 Instant.ofEpochSecond()

      【讨论】:

        【解决方案6】:

        简单直接的解决方案将 (KOTLIN)

                    val timeStamp:Long=559585985988
                    val sdf = SimpleDateFormat("hh:mm:ss a - MMM dd,yyyy", Locale.getDefault())
                    val tz = TimeZone.getDefault()
                    val now = Date()
                    val offsetFromUtc = tz.getOffset(now.time)
                    val localeTimeStr = sdf.format(timeStamp + offsetFromUtc) //add the offset to get the local time from the epoch timestamp
        

        【讨论】:

          猜你喜欢
          • 2017-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-30
          • 1970-01-01
          • 2017-05-17
          • 2021-12-25
          • 1970-01-01
          相关资源
          最近更新 更多