java - 将秒转换为相对时间
问题描述
我一直在尝试制作一个应用程序,我需要将时间以秒为单位转换为相对时间,有人可以帮助我做到这一点。例子 :
time in seconds:1594564500
date:12 July 2020 20:05:00 GMT+05:30
relative time: In 5 days
解决方案
我一直在尝试制作一个应用程序,我需要将时间以秒为单位转换为相对时间
一种简单的方法是从给定时间获取Instant
(例如instant
)的对象,然后使用Instant.now().until(instant, ChronoUnit.DAYS)
.
演示:
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
// Create an object of Instant from the given no. of seconds
Instant instant = Instant.ofEpochSecond(1594564500);
// Get the no. of days from the current time to the given time
long days = Instant.now().until(instant, ChronoUnit.DAYS);
System.out.println("No. of days: " + days);
// ##########If you want to get date-time information##########
// Create OffsetDateTime from Instant
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);// UTC
System.out.println("Date-time at UTC:" + odt);
odt = instant.atOffset(ZoneOffset.ofHours(1));// GMT
System.out.println("Date-time at GMT:" + odt);
// Get LocalDateTime from OffsetDateTime
LocalDateTime ldt = odt.toLocalDateTime();
System.out.println("Date-time without time-zone infromation: " + ldt);
}
}
输出:
No. of days: 5
Date-time at UTC:2020-07-12T14:35Z
Date-time at GMT:2020-07-12T15:35+01:00
Date-time without time-zone infromation: 2020-07-12T15:35
一些重要的注意事项:
- 将 Java SE 8 日期时间类向后移植到 Java SE 6 和 7:检查ThreeTen-Backport和How to use ThreeTenABP
推荐阅读
- cucumber - 如何在testng runner类的特征标签中一一执行特征文件中提到的顺序
- mysql - 在子查询mysql中使用父查询的id列
- xmpp - 无法在 ejabberd-18-06 上处理自定义 iq
- android - 用于在 Android 应用中调试和发布的分析属性
- react-native - 在本机反应中选择时如何更改列表项背景颜色?
- android - 为什么“doOnError”在“err->{}”没有传递给“subscribe()”方法之前不起作用
- algorithm - 我如何理解hackerrank中一个问题的具体解决方案?
- javascript - 将 id 分配给从 JSON 文件动态创建的 div
- google-analytics - 在 Google 跟踪代码管理器上设置实时环境的正确方法是什么?
- postgresql - 如何在查询中准确找到平均值