【问题标题】:Turning timeInMills to a 24hour/Date将 timeInMillis 转换为 24 小时/日期
【发布时间】:2018-10-15 13:12:07
【问题描述】:
是否有任何源代码可以将 timeInMills 转换为 24 小时/日期,例如来自 messenger 应用程序。当 timeInMills 低于 24 小时时,它将像这样返回 16:15,但是当超过 24 小时时,它将像这样返回 THU at 16:15。我目前正在创建一个聊天应用程序,我想将它添加到我的应用程序中。
【问题讨论】:
标签:
java
android
epoch
milliseconds
time-format
【解决方案1】:
编辑
注意这一行:long last24hTimestamp = current - MILLISECONDS_PER_DAY;
我代表 UTC 时间计算。
要获取当地时间,您应该考虑时区。
所以基本上你必须计算时间戳timeInMillis是否在过去 24 小时内,然后使用一种格式,否则使用另一种格式。
这将对您有所帮助:
public static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;// In real app you should pre-calculate this value
public static final String RECENT_DATE_FORMAT = "HH:mm";
public static final String OLD_DATE_FORMAT = "E' at 'HH:mm";
public static String displayTime(long timestamp) {
long current = System.getCurrentTimeMillis();
long last24hTimestamp = current - MILLISECONDS_PER_DAY;
if (timestamp > last24hTimestamp) {
// Received message within a day, use first format
SimpleDateFormat sdf = new SimpleDateFormat(RECENT_DATE_FORMAT);
return sdf.format(new Date(timestamp));
} else {
// Message is older than 1 day. Use second format
}
}
你应该注意的事情:
如果您的应用在多个地方运行,请考虑使用时区/本地化进行解析
如果您使用的是 java 8,请尝试使用 DateTimeFormatter。它是线程安全的,您可以使用每个日期格式的静态实例,无需在每次要格式化日期时初始化 SimpleDateFormat
【解决方案2】:
java.time
对于在 Java 中处理日期或时间,我推荐 java.time,现代 Java 日期和时间 API。
static DateTimeFormatter lessThan24HoursAgoFormatter
= DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
static DateTimeFormatter moreThan24HoursAgoFormatter
= DateTimeFormatter.ofPattern("EEE 'at' HH:mm", Locale.ENGLISH);
static ZoneId zone = ZoneId.of("America/Yakutat");
public static String getDisplayString(long timeInMills) {
ZonedDateTime dateTime = Instant.ofEpochMilli(timeInMills)
.atZone(zone)
.truncatedTo(ChronoUnit.MINUTES);
ZonedDateTime currentTimeYesterday = ZonedDateTime.now(zone).minusDays(1);
if (dateTime.isAfter(currentTimeYesterday)) {
return dateTime.format(lessThan24HoursAgoFormatter);
} else {
return dateTime.format(moreThan24HoursAgoFormatter);
}
}
刚刚运行
-
getDisplayString(1_525_402_083_258L) 返回Thu at 18:48。
-
getDisplayString(1_525_490_972_172L) 只返回了 19:29。
请把你想要的时区放在我放在美国/雅库塔特的地方。我建议您插入检查以确保毫秒表示不超过一周前而不是将来的时间,因为在这些情况下返回的字符串会令人困惑。
也有可能存在一个库,它将格式化一个类似于你想要的字符串。使用您的搜索引擎。
问题:我可以在 Android 上使用java.time 吗?
是的,java.time 在较旧和较新的 Android 设备上运行良好。它只需要至少 Java 6。
- 在 Java 8 及更高版本以及新的 Android 设备上(据我所知,从 API 级别 26 开始)新的 API 是内置的。
- 在 Java 6 和 7 中,获取 ThreeTen Backport,即新类的后向端口(对于 JSR 310,ThreeTen 是现代 API 的首次描述)。
- 在(较旧的)Android 上,使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。确保从包
org.threeten.bp 和子包中导入日期和时间类。
链接