Time conversion from seconds to date issue

Sid*_*ria -1 java time date kotlin

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))
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Arv*_*ash 7

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
Run Code Online (Sandbox Code Playgroud)

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Output:

2012-07-09T17:42:43Z
Run Code Online (Sandbox Code Playgroud)

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

Output:

Mon Jul 09 18:42:43 BST 2012
Run Code Online (Sandbox Code Playgroud)

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.

  • 这是因为我在英国(英国夏令时间)并且“java.util.Date”使用默认时区。这就是为什么使用现代日期时间 API(例如“java.time.Instant”)是更明智的做法,在这种 API 中,您不仅可以处理和呈现日期和时间,还可以处理和呈现时区信息。 (2认同)

Jon*_*oni 6

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

val milliSeconds = 1341855763000
val date = Date(milliSeconds)
Run Code Online (Sandbox Code Playgroud)