gpt4 book ai didi

java - Java中日期的转换

转载 作者:行者123 更新时间:2023-12-02 07:43:31 24 4
gpt4 key购买 nike

为什么如果我将日期从毫秒转换为天,然后再转换回来,从天转换为毫秒,该日期会发生变化?

例如:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2012-06-02");
System.out.println(date);
Long dateAsDays = TimeUnit.MILLISECONDS.toDays(date.getTime());

System.out.println(
new Date(
TimeUnit.DAYS.toMillis(dateAsDays)
) );

将打印:

Sat Jun 02 00:00:00 GMT+03:00 2012

Fri Jun 01 03:00:00 GMT+03:00 2012

如何在此转换中保存该月的日期?为什么这段代码不能正常工作?

最佳答案

当您以天为单位获取日期时,日期会变得不太准确。您现在处于 GMT+3,因此 12:00 GMT 对您来说就是 3:00。来自 TimeUnit class reference :

convert

public long convert(long sourceDuration, TimeUnit sourceUnit)

Convert the given time duration in the given unit to this unit. Conversions from finer to coarser granularities truncate, so lose precision. For example converting 999 milliseconds to seconds results in 0. Conversions from coarser to finer granularities with arguments that would numerically overflow saturate to Long.MIN_VALUE if negative or Long.MAX_VALUE if positive. For example, to convert 10 minutes to milliseconds, use: TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES)

关于java - Java中日期的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11246633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com