5

Is there a way to get the current time of the day in seconds? Notice I am asking the time of the day, not UTC time.

What I want is a value (in seconds) between the range 0 - 86,400 (12:00AM - 11:59PM). I'm working on an app that works on a daily basis, and when the day ends, the time (in seconds) should restart back at 0 again.

So let's say it's 10:00AM. I should be getting 36,000 seconds, and if my time is 5:00PM, I should be getting 61,200 seconds.

PS: I do not know the time before hand. The program will figure it out by itself using a currentTime() function.

SVCS1994
  • 213
  • 1
  • 3
  • 14

5 Answers5

7

With Java 8, you could create a Duration instance.
For example :

LocalDateTime date = LocalDateTime.now();
long seconds = Duration.between(date.withSecond(0).withMinute(0).withHour(0), date).getSeconds();

Or more simply you could convert the LocalDateTime to a LocalTime instance and then apply the toSecondOfDay() method :

LocalDateTime date = LocalDateTime.now();
int seconds = date.toLocalTime().toSecondOfDay();

From the java.time.LocalTime javadoc :

public int toSecondOfDay()

Extracts the time as seconds of day, from 0 to 24 * 60 * 60 - 1.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
3

Use a java.time.LocalTime and a java.time.temporal.ChronoField:

// 10:00 AM
LocalTime d = LocalTime.of(10, 0);
System.out.println(d.get(ChronoField.SECOND_OF_DAY)); // 36000

// 05:00 PM
d = LocalTime.of(17, 0);
System.out.println(d.get(ChronoField.SECOND_OF_DAY)); // 61200

// 23:59:59
d = LocalTime.of(23, 59, 59);
System.out.println(d.get(ChronoField.SECOND_OF_DAY)); // 86399

// midnight
d = LocalTime.of(0, 0);
System.out.println(d.get(ChronoField.SECOND_OF_DAY)); // 0

This prints:

36000
61200
86399
0


Notes:

  • That's just examples. If you want to get the value from the current time, just use LocalTime.now() (or LocalTime.now(ZoneId.of("timezone-name")) as pointed by @Ole V.V.'s answer).

    As a timezone-name, always use IANA timezones names (always in the format Continent/City, like America/Sao_Paulo or Europe/Berlin). Avoid using the 3-letter abbreviations (like CST or PST) because they are ambiguous and not standard. You can get a list of available timezones (and choose the one that fits best your system) by calling ZoneId.getAvailableZoneIds().

  • You can also call d.toSecondOfDay() if you want (it's equivalent, as get(ChronoField) internally calls toSecondOfDay).
  • Problem with this solution is that I need to know before hand at what time do I want to get the seconds for. It won't work if I don't pass in the exact time as a parameter to the LocalTime.of() function. – SVCS1994 Jun 26 '17 at 19:28
  • 2
    That's just examples. If you want to get the value from the current time, just use `LocalTime.now()` - I've updated the answer btw –  Jun 26 '17 at 19:30
  • Please pass an explicit time zone to `LocalTime.now()`. Otherwise fine. – Ole V.V. Jun 26 '17 at 19:35
2

I suggest:

    int secondsOfDay = LocalTime.now(ZoneId.of("Europe/Rome")).toSecondOfDay();

Points to note:

  • Use an explicit time zone to remind the reader and yourself that the choice of time zone matters and that you have made a conscious choice. Either ZoneId.systemDefault(), or even better is if it would make sense in your situation to give a named zone like for example ZoneId.of("Europe/Rome").
  • The snippet converts 10:00 AM to 36,000 no matter when the day began; because of summer time and other anomalies it may not have begun at 0:00 midnight, and there may be a gap or overlap early in the morning. To get the true number of seconds since the day began, you will need some calculation involving LocalDate.now(yourTimeZone).atStartOfDay(yourTimeZone).
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You can just convert the seconds minutes hour fields into seconds and add them up

Calendar c = new GregorianCalendar();
int totalSecs = c.get(Calendar.SECOND) + 60 * c.get(Calendar.MINUTE) + 3600 * c.get(Calendar.HOUR_OF_DAY);
davidxxx
  • 125,838
  • 23
  • 214
  • 215
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 4
    When the asker tags the question with the `java.time` package, please don’t suggest using the long outdated `Calendar` class. Even if this tag wasn’t present, you shouldn’t, or at least not without mentioning other options, since the Java date & time API in the mentioned package is much better, much more programmer friendly, both in general and for thins particular case. – Ole V.V. Jun 26 '17 at 19:09
  • 1
    So even though I get the answer I wanted, his solution is not efficient/good enough? @OleV.V. – SVCS1994 Jun 26 '17 at 19:11
  • @SVCS1994 Are you using Java 8's `java.time` package? You didn't really specify in your question, other than the tag which could have mislead you. – Jonny Henly Jun 26 '17 at 19:13
  • Yes. I want to because I read it's more efficient, but if @ControlAltDel 's solution is as efficient as if I used that package, then I guess I can use his solution. I'm new with Java 8 packages btw. – SVCS1994 Jun 26 '17 at 19:15
  • 1
    @ControlAltDel I changed `HOUR` to `HOUR_OF_DAY` as `HOUR` is a 12-hour clock. Otherwise for PM hours, the result will be inaccurate. – davidxxx Jun 26 '17 at 19:23
  • 3
    IMHO you don’t want to do the “hand calculation” in the answer when there are standard library classes that can do it for you. The latter is clearer to read and less errorprone. Second, while the answer gives the correct result (as far as I can tell), the classes `Calendar` and `GregorianCalendar` (did I mention they are long outdated) are generally a mess to work with compared with the programmer friendly modern classes, so you will want to make it a habit to use the latter. Just my € 0.02. @SVCS1994 – Ole V.V. Jun 26 '17 at 19:25
  • 1
    @ControlAltDel I upvote because even if it not the expected answer nowadays (with Java 8), it doesn't deserve a negative evaluation either. Personally, I would probably add that the solution is for case where Java 8 cannot be used. – davidxxx Jul 01 '17 at 07:33
0

You could use the SimpleDateFormat to extract the hours minutes and seconds. It works on Java 7 and Java 6 and Java 8, and it adapts to your local time and timezone:

String timeNowHMS[] = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH)
        .format(System.currentTimeMillis())
        .split(":");

int secondsPassedInTheDay =
    Integer.parseInt(timeNowHMS[0]) * 60 * 60
        + Integer.parseInt(timeNowHMS[1]) * 60
        + Integer.parseInt(timeNowHMS[2]);

Mr-IDE
  • 7,051
  • 1
  • 53
  • 59
  • Thanks for showing how complicated and hand-held this is using `SimpleDateFormat`. One more argument against using it (java.time, the modern Java date and time API can work on Java 6, 7 and 8 too). – Ole V.V. Apr 02 '19 at 10:16