Home > database >  Converting current time to Seconds in Java
Converting current time to Seconds in Java

Time:11-03

I have a value of 64800 which is 18:00 in seconds, so I am in need of converting current time to seconds format which I would need to compare if it is after the 64800 or before.

int minutes=64800;
long hours = TimeUnit.SECONDS.toHours(Long.valueOf(minutes));
long remainMinutes = minutes - TimeUnit.HOURS.toSeconds(hours);
System.out.println(String.format("d:d", hours, remainMinutes));

If I use System.currentTimeMillis I am unable to convert it

CodePudding user response:

You can use Duration to get the desired result.

Demo:

import java.time.Duration;

public class Main {
  public static void main(String[] args) {
    Duration duration = Duration.ofSeconds(64800);
    String desiredValue = String.format("d:d", duration.toHoursPart(), duration.toMinutesPart());
    System.out.println(desiredValue);
  }
}

Output:

18:00

Learn more about the modern Date-Time API from Trail: Date Time and about the Duration through Q/As tagged with duration.

CodePudding user response:

The solution based in Duration is the best (IMO), however, there is another way to get the current day seconds from 00:00 in case you want to do it using System.currentTimeMillis() and maths:

long epoch = System.currentTimeMillis() / 1000L; // Epoch in seconds
long todaySeconds = epoch % (24*3600); // Current day seconds from 00:00

With todaySeconds you can compare with 64800 or whatever other value, but IMPORTANT, the todaySeconds doesn't include timezone info, so, if the "real" time is not in UTC, this doesn't wotk.

To get the hour and minute:

long hour = todaySeconds / 3600;
long minute = todaySeconds % 3600 / 60;
  • Related