I have been trying to make an app where I need to convert time in seconds to relative time can someone help me to do that. example :
time in seconds:1594564500
date:12 July 2020 20:05:00 GMT+05:30
relative time: In 5 days
I have been trying to make an app where I need to convert time in seconds to relative time can someone help me to do that. example :
time in seconds:1594564500
date:12 July 2020 20:05:00 GMT+05:30
relative time: In 5 days
I have been trying to make an app where I need to convert time in seconds to relative time
A simple way is to get an object of Instant
(say, instant
) from the given time and then use Instant.now().until(instant, ChronoUnit.DAYS)
.
Demo:
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);
}
}
Output:
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
Some important notes:
LocalDateTime
drops the important information of time-zone and zone-offset from it. Choose the right date-time object from the list given below as per your requirement:You would use something along the lines of:
long timeInSeconds = 1594564500;
long interval;
String relative;
long difference = Math.abs(System.currentTimeMillis() - (timeInSeconds * 1000));
if (difference > DateUtils.WEEK_IN_MILLIS) {
interval = difference / DateUtils.WEEK_IN_MILLIS;
relative = " weeks";
} else if (difference > DateUtils.DAY_IN_MILLIS) {
interval = difference / DateUtils.DAY_IN_MILLIS;
relative = " days";
} else if (difference > DateUtils.HOUR_IN_MILLIS) {
interval = difference / DateUtils.HOUR_IN_MILLIS;
relative = " hours";
} else {
interval = Long.MIN_VALUE;
relative = "Unknown";
}
interval = Math.round(interval);
Log.d("Relative Time", String.valueOf(interval) + relative);