[Solved] How to get time from user with respect to timezone


    String userTimeZone = "Asia/Samarkand";
    String userDate = "2018-07-05";

    ZoneId zone = ZoneId.of(userTimeZone);
    Instant dbInstant = LocalDate.parse(userDate)
            .atStartOfDay(zone)
            .toInstant();

    System.out.println(dbInstant);

This prints what you had expected:

2018-07-04T19:00:00Z

I don’t know MongoDB’s JDBC driver, but I assume it would be happy to accept an Instant and store it in UTC in the database.

GMT+05:00 is not really a time zone, it’s a GMT offset. If your user is in a time zone that uses the same UTC offset always, it would work. But politicians tend to change their minds, so even if that time zone doesn’t use summer time (DST), it may do in a couple of years. And very many time zones already do. Therefore your user should pick a proper time zone like Asia/Tashkent, for example.

Edit: I understand from your comment that MongoDB expects a java.util.Date object. Funny and old-fashioned, but in that case the conversion is straightforward when you know how:

    Date dbDate = Date.from(dbInstant);
    System.out.println(dbDate);

On my computer in Europe/Copenhagen time zone this printed:

Wed Jul 04 21:00:00 CEST 2018

Don’t be fooled: this is the correct time. Date.toString (implicitly called through System.out.println) grabs my JVM’s time zone setting and uses it for generating the string. The Date itself doesn’t have a time zone in it and holds the same point in time as the Instant.

Link: Oracle tutorial: Date Time

0

solved How to get time from user with respect to timezone