Skip to content Skip to sidebar Skip to footer

For A Given Date Object, Capture It's Value Relevant To Gmt Timezone

In my application running on Java 8, I have a Date object. The timezone for this object depends on the client's location. At one particular point, I need to convert this Date to GM

Solution 1:

java.time and JDBC 4.2

The answer is in @BasilBourque’s comment: use OffsetDateTime.

PreparedStatementyourPreparedStatement= yourDatabaseConnection.prepareStatement(
            "select smth from your_table where your_time_stamp_col < ?;");
    OffsetDateTimegmtTime= OffsetDateTime.now(ZoneOffset.UTC);
    yourPreparedStatement.setObject(1, gmtTime);

This requires a JDBC 4.2 compliant JDBC driver, I think that about all of us are using that by now. Which is good because it allows us to bypass java.sql.Timestamp and the other date-time types in java.sql. They are all poorly designed and long outdated.

As others have said, neither of the outdated classes Date and Timestamp have any time zone or offset from UTC/GMT.

Some related questions

Solution 2:

First of all Date class is part of the old outdated (no pun intended) infrastructure. If it is at all possible get rid of it and just use java.time package. But if you must work with Date then your problem with time zone is not a problem. your line System.out.println(gmtDate); only prints it with your local time zone, since the system assumes that it is the best option. But regardless of that Date holds a particular moment in time in milliseconds since January 1, 1970, 00:00:00 GMT. Class Date has methods compareTo(), after() and before() that allow you to compare 2 Dates. Also Date has method getTime() that returns you the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this date. So you can compare the long values. But again, The best option is to switch to java.time package and classes Instant and ZonedDateTime (and others) have methods compareTo(), isAfter() and isBefore().

Solution 3:

You misunderstand the semantics of date time classes. java.util.Date is a specific point in time, an instant, it has no time zone associated with it. However if you have a time zone you can ask the time zone for the time of that java.util.Date.

java.sql.TimeStamp is the equivalent of java.time.LocalDateTime. It is not an instant and has no time zone associated with it.

Post a Comment for "For A Given Date Object, Capture It's Value Relevant To Gmt Timezone"