我正在尝试在 android studio 中创建一个聊天应用程序。我有一个时间戳这样说 - 1694603269045。现在我想将此时间戳转换为人类可读的方式,例如一分钟前或一小时前。我将进入我的故事视图模式,用户将能够看到他的朋友何时上传故事/状态。我需要这个 One Minute Ago 字符串,以便我可以在文本视图中使用它。这可能吗?
我试图找到一些解决方案,但大多数都与我在 Java 中需要的 javascript 相关。 字符串需要是这样的 -
这在 Java 中是否可能以某种方式实现?谢谢你。
您可以根据您的
timestamp创建一个
Instant
并计算它与 Duration
之间的 Instant.now()
。
public static void main(String[] args) {
// your timestamp
long timestamp = 1694603269045L;
// convert to an Instant
Instant then = Instant.ofEpochMilli(timestamp);
// get "now"
Instant now = Instant.now();
// calulate the Duration
Duration duration = Duration.between(then, now);
// print the minutes part
System.out.println(duration.toMinutesPart() + " minutes ago");
}
这是刚刚打印的
47 minutes ago
例如,如果您想在分钟为 0 但小时不是 0 时从分钟切换到小时,则必须检查哪些值(小时、分钟、秒等)实际上为零。这将在 13 分钟内打印出
0 minutes ago
,您可能想要涵盖类似的情况。