从秒到日期的时间转换 [英] Time conversion from seconds to date issue
问题描述
我有以下Long
变量,以秒为单位保存纪元值,我正尝试将其转换为Date
.
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
推荐答案
输出比我预期的要远.我哪里出问题了?
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
该值已经在milliseconds
中,并且使用TimeUnit.SECONDS.toMillis(seconds)
您将其错误地乘以1000
.
The value is already in milliseconds
and by using TimeUnit.SECONDS.toMillis(seconds)
you are wrongly multiplying it by 1000
.
import java.time.Instant;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.ofEpochMilli(1341855763000L);
System.out.println(instant);
}
}
输出:
2012-07-09T17:42:43Z
使用旧版java.util.Date
:
import java.util.Date;
public class Main {
public static void main(String[] args) {
System.out.println(new Date(1341855763000L));
}
}
输出:
Mon Jul 09 18:42:43 BST 2012
我建议您从过时且容易出错的java.util
日期时间API和SimpleDateFormat
切换到跟踪:日期时间了解更多有关现代日期时间API的信息. a> .
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.
这篇关于从秒到日期的时间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!