gpt4 book ai didi

java - File.lastmodified() 生成错误的日期和月份

转载 作者:行者123 更新时间:2023-12-01 16:43:42 25 4
gpt4 key购买 nike

我使用 File.getlastmodified() 来获取文件的最后修改,但由于某种原因(可能是 UIT)它打印了错误的日期和月份(年份很好)

我最后用上述方法修改并将其保存为 Long

//理想情况下,这应该将最后修改的内容转换为人类可读取的格式但它返回错误的月份和日期

喜欢---->2018年11月27日

显示为--->2018年10月28日

c = Calendar.getInstance(); 

Long epoch = files[i].lastModified();

epoch+=32400L;

c.setTimeInMillis(epoch); //im converting the milliseconds to human readable formate

int year=c.get(Calendar.YEAR);
int month=c.get(Calendar.MONTH);
int day=c.get(Calendar.DATE);

最佳答案

该值不正确。您使用日历的方式不正确。检查文档,您可以看到为 Month 返回的值。

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year.

Source

现在,就这一天而言,我怀疑增加 32 秒可能是问题所在。但最有可能的是时区。事实上,该方法在 GMT 上返回一个值。

<小时/>

请注意,我已检查修改了“2019-04-17 14:52:13”的文件并获得了正确的结果。此外,您可以使用 SimpleDateFormat 实例格式化 Calendar,而不是像这样提取值。

private static String formatEpoch(long epoch) {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(epoch));
}

或者,我们永远不会提及这一点,使用更新的 API 与 Instant 进行日期。

private static String formatEpoch(long epoch) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
return formatter.format(Instant.ofEpochMilli(epoch).atZone(ZoneId.systemDefault()));
}

瞬时是 GMT 的日期时间,因此我们在使用 DateTimeFormatter 对其进行格式化之前添加区域设置时区,以提供如下值:

2019-04-17T14:52:13.118

关于java - File.lastmodified() 生成错误的日期和月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283585/

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