首页 > 解决方案 > 将秒转换为相对时间

问题描述

我一直在尝试制作一个应用程序,我需要将时间以秒为单位转换为相对时间,有人可以帮助我做到这一点。例子 :

time in seconds:1594564500  
date:12 July 2020 20:05:00 GMT+05:30 
relative time: In 5 days 

标签: javaandroiddatetimetimeinstant

解决方案


我一直在尝试制作一个应用程序,我需要将时间以秒为单位转换为相对时间

一种简单的方法是从给定时间获取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

一些重要的注意事项:

  1. 从此处了解有关现代日期时间 API 的更多信息。
  2. LocalDateTime从中删除时区和区域偏移的重要信息。根据您的要求,从下面给出的列表中选择正确的日期时间对象:

在此处输入图像描述

  1. 将 Java SE 8 日期时间类向后移植到 Java SE 6 和 7:检查ThreeTen-BackportHow to use ThreeTenABP

推荐阅读