Will this give me the correct local time of the user?

240 Views Asked by At

I need to figure out a way to get the user's local time reliably. After researching, one potential solution could be:

Day of the week in user's location:

int dayOfWeek = ZonedDateTime.now(Clock.systemDefaultZone()).getDayOfWeek().ordinal();

Actual time in the user's location:

LocalDateTime.now(Clock.systemDefaultZone()));

Is this all correct? Am I correct to be using Clock.systemDefaultZone()? If so, I wonder how Clock.systemDefaultZone() is able to magically figure out the correct time zone?

2

There are 2 best solutions below

2
On

Note that in your first example, you don't need a ZonedDateTime, a LocalDate would do since you only care about the day in the week, not the time in that day. Also note that LocalDate.now() uses the system default clock and you don't need to explicitly specifly it.

Regarding that default clock, Clock.systemDefaultZone() is based on the system default time zone, which is retrieved by querying TimeZone.getDefault():

Gets the default TimeZone of the Java virtual machine. If the cached default TimeZone is available, its clone is returned. Otherwise, the method takes the following steps to determine the default time zone.

  • Use the user.timezone property value as the default time zone ID if it's available.
  • Detect the platform time zone ID. The source of the platform time zone and ID mapping may vary with implementation.
  • Use GMT as the last resort if the given or detected time zone ID is unknown. The default TimeZone created from the ID is cached, and its clone is returned. The user.timezone property value is set to the ID upon return.
5
On

It's as simple as this:

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class Main {
    public static void main(String[] args) {
        // Local date
        LocalDate today = LocalDate.now();
        System.out.println(today);

        // Local time
        LocalTime now = LocalTime.now();
        System.out.println(now);

        // Local date and time
        LocalDateTime ldt = LocalDateTime.now();
        System.out.println(ldt);

        // Day of week
        DayOfWeek dayOfWeek = today.getDayOfWeek();
        System.out.println(dayOfWeek);
        System.out.println(dayOfWeek.getValue());
    }
}

Output for my time-zone:

2020-10-03
17:47:57.426833
2020-10-03T17:47:57.426943
SATURDAY
6