Time conversion from seconds to date issue

荒凉一梦 提交于 2021-02-05 12:20:55

问题


I have the following Long variable holding epoch value in seconds, which I'm trying to convert into a Date.

val seconds = 1341855763000
val date = Date(TimeUnit.SECONDS.toMillis(seconds))

The output is way off than I expected. Where did I go wrong?

Actual: Wed Sep 19 05:26:40 GMT+05:30 44491
Expected: Monday July 9 11:12:43 GMT+05:30 2012

回答1:


The output is way off than I expected. Where did I go wrong?

Actual: Wed Sep 19 05:26:40 GMT+05:30 44491
Expected: Monday July 9 11:12:43 GMT+05:30 2012

The value is already in milliseconds and by using TimeUnit.SECONDS.toMillis(seconds) you are wrongly multiplying it by 1000.

By using the modern date-time API:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.ofEpochMilli(1341855763000L);
        System.out.println(instant);
    }
}

Output:

2012-07-09T17:42:43Z

By using legacy java.util.Date:

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        System.out.println(new Date(1341855763000L));
    }
}

Output:

Mon Jul 09 18:42:43 BST 2012

I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.




回答2:


The value you have is not in seconds but in milliseconds. Remove the "seconds to millis" conversion.

val milliSeconds = 1341855763000
val date = Date(milliSeconds)



回答3:


Your value : 1341855763000 is not in seconds, it is in milliseconds. The current timestamp is : new Date().getTime() => 1598612990351 Same number of digits than : 1341855763000

If you multiply 1341855763000 by 1000 (as you say), it gives the year : 44491 after JC :D Have a good day




回答4:


I think your time is actually in milliseconds. If I convert 1341855763000 using this website it gives me your expected time and this as well:

fun main() {
  val millis = 1341855763000
  val date = Date(millis)
  println(date)
}

Alternatively, you can also use seconds:

fun main() {
  val seconds = 1341855763L
  val date = Date(TimeUnit.SECONDS.toMillis(seconds))
  println(date)
}

Just divide by 1000.



来源:https://stackoverflow.com/questions/63632592/time-conversion-from-seconds-to-date-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!