【发布时间】:2020-09-04 16:43:28
【问题描述】:
我不确定这是否可以提高效率,但我需要获取自 unix/epoch 时间戳以来经过的天数,其中时间本身不是因素,只有日期比较现在。
Example 1:
Timestamp is : 3rd September 14:35
Compared to now which is: 4th September 00:35
Days difference = 1
Example 2:
Timestamp is: 3rd September 23:55
Compared to now which is: 4th September 00:35
Days difference = 1
Example 3:
Timestamp is: 2nd September 02:23
Compared to now which is: 4th September 00:35
Days difference = 2
为此,我有以下代码:
String epoch = "1599134401" // the unix/epoch timestamp in seconds
Long epochMillis = Long.valueOf(epoch) * 1000;
Date epochDateObj = new Date(epochMillis);
Calendar tsCal = Calendar.getInstance();
tsCal.setTime(epochDateObj);
tsCal.set(Calendar.HOUR_OF_DAY, 0);
tsCal.set(Calendar.MINUTE, 0);
tsCal.set(Calendar.SECOND, 0);
tsCal.set(Calendar.MILLISECOND, 0);
Calendar today = Calendar.getInstance();
today.set(Calendar.HOUR_OF_DAY, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
today.set(Calendar.MILLISECOND, 0);
long diffInMillies = Math.abs(today.getTime().getTime() - tsCal.getTime().getTime());
long diff = TimeUnit.DAYS.convert(diffInMillies, TimeUnit.MILLISECONDS);
if(diff > 1) {
return diff + " days";
} else {
return diff + " day";
}
上面的代码有效,但对我来说,对于这样一个相当小的东西来说,它似乎相当复杂。
有什么优化建议吗?也许有一些我不知道的功能。它是一个使用相当旧的 SDK(回到 Android 4.1)的 Android 应用程序。
【问题讨论】:
-
我建议你不要使用
Date和Calendar。这些课程设计不佳且早已过时。而是使用Instant、LocalDate、ZoneId和ChronoUnit,均来自java.time, the modern Java date and time API。 -
您要计算哪个时区?首先,Unix 纪元在某些时区是 1969 年 12 月 31 日,在其他时区是 1970 年 1 月 1 日。