tl;dr

Use the ZoneId & ZonedDateTime classes found in the java.time package.

ZonedDateTime.now()  // Implicitly applies the JVM’s current default time zone.

Better to specify your desired/expected time zone explicitly.

ZonedDateTime.now(
    ZoneId.of( "Africa/Tunis" ) 
)

java.time

The modern approach uses the java.time classes that years ago supplanted the terrible legacy classes such as Timestamp, Calendar, Date, TimeZone, and SimpleDateFormat.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

Capture the current moment as seen through the wall-clock time used by the people of a particular region, that time zone named above.

ZonedDateTime zdt = ZonedDateTime.now( z ) ;


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Answer from Basil Bourque on Stack Overflow
🌐
Oracle
forums.oracle.com › ords › apexds › post › how-to-get-timestamp-along-with-timezone-in-java-2000
How to get timestamp along with timezone in java - Oracle Forums
May 4, 2023 - Hello, How to get a timestamp with timezone in java. import java.util.Date; import java.util.TimeZone; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); String dateV...
🌐
Blogger
javarevisited.blogspot.com › 2012 › 01 › get-current-date-timestamps-java.html
How to get current Date Timestamps in Java on GMT or Local Timezone? Example Tutorial
By the way, from JDK 8 onwards you can use modern classes like LocalTime, LocalDate, Instant, and ZonedDateTime to get the current date and timestamp in your local timzezon or any given timezone like UTC or GMT
Top answer
1 of 4
4

tl;dr

Use the ZoneId & ZonedDateTime classes found in the java.time package.

ZonedDateTime.now()  // Implicitly applies the JVM’s current default time zone.

Better to specify your desired/expected time zone explicitly.

ZonedDateTime.now(
    ZoneId.of( "Africa/Tunis" ) 
)

java.time

The modern approach uses the java.time classes that years ago supplanted the terrible legacy classes such as Timestamp, Calendar, Date, TimeZone, and SimpleDateFormat.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  

Capture the current moment as seen through the wall-clock time used by the people of a particular region, that time zone named above.

ZonedDateTime zdt = ZonedDateTime.now( z ) ;


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
2 of 4
0

You can get the timestamp with time zone with this method :

public static long getTimestampWithGMT() {
    long timestamp = System.currentTimeMillis() / 1000;
    int offset = (TimeZone.getDefault().getRawOffset() + TimeZone.getDefault().getDSTSavings()) / 1000;

    return timestamp + offset;
}
🌐
Baeldung
baeldung.com › home › java › java dates › set the time zone of a date in java
Set the Time Zone of a Date in Java | Baeldung
September 8, 2024 - We’ve used Java 8’s ZonedDateTime to represent a date-time with a time zone. In Java 7, setting the time-zone is a bit tricky. The Date class (which represents a specific instant in time) doesn’t contain any time zone information. First, let’s get the current UTC date and a TimeZone object:
Top answer
1 of 14
107

Date is always UTC-based... or time-zone neutral, depending on how you want to view it. A Date only represents a point in time; it is independent of time zone, just a number of milliseconds since the Unix epoch. There's no notion of a "local instance of Date." Use Date in conjunction with Calendar and/or TimeZone.getDefault() to use a "local" time zone. Use TimeZone.getTimeZone("Europe/Madrid") to get the Madrid time zone.

... or use Joda Time, which tends to make the whole thing clearer, IMO. In Joda Time you'd use a DateTime value, which is an instant in time in a particular calendar system and time zone.

In Java 8 you'd use java.time.ZonedDateTime, which is the Java 8 equivalent of Joda Time's DateTime.

2 of 14
75

As Jon Skeet already said, java.util.Date does not have a time zone. A Date object represents a number of milliseconds since January 1, 1970, 12:00 AM, UTC. It does not contain time zone information.

When you format a Date object into a string, for example by using SimpleDateFormat, then you can set the time zone on the DateFormat object to let it know in which time zone you want to display the date and time:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

If you want the local time zone of the computer that your program is running on, use:

df.setTimeZone(TimeZone.getDefault());
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 355651 › converting-a-timestamp-to-a-different-timezone
java - converting a timestamp to a different timezone | DaniWeb
Date (and Timestamp) will always display the date in the local timezone, regardless of what timezone you used to parse the data, so "1" is not only possible, it is the default, and "2" (if really just needs the millisecond difference) is simply ...
🌐
Medium
medium.com › @williampuk › sql-timestamp-and-jdbc-timestamp-deep-dive-7ae0ea91e237
SQL Timestamp, JDBC Timestamp and multiple Time Zones | by William Puk | Medium
February 19, 2023 - The timestamp_val is first set as 2021–03–14 02:01:01.0 , then converted from the session time zone (UTC+8) to UTC and stored as 2021–03–13 18:01:01.0 . In the retrieval, the value 2021–03–13 18:01:01.0 is converted from UTC to the session time zone (UTC+5). The value JDBC driver received is therefore 2021–03–13 23:01:01.0 . By passing a Calendar with ‘America/New_York’ time zone to the method getTimestamp , it constructed a java.sql.Timestamp with the instant in time 2021–03–13 23:01:01.0 UTC-5 which is equivalent to 2021–03–14 12:01:01.0 UTC+8 .
Top answer
1 of 8
127

Although it is not explicitly specified for setTimestamp(int parameterIndex, Timestamp x), drivers have to follow the rules established by the setTimestamp(int parameterIndex, Timestamp x, Calendar cal) javadoc (emphasis mine):

Sets the designated parameter to the given java.sql.Timestamp value, using the given Calendar object. The driver uses the Calendar object to construct an SQL TIMESTAMP value, which the driver then sends to the database. With a Calendar object, the driver can calculate the timestamp taking into account a custom time zone. If no Calendar object is specified, the driver uses the default time zone, which is that of the virtual machine running the application.

When you call with setTimestamp(int parameterIndex, Timestamp x) the JDBC driver uses the time zone of the virtual machine to calculate the date and time of the timestamp in that time zone. This date and time is what is stored in the database, and if the database column does not store time zone information, then any information about the zone is lost (which means it is up to the application(s) using the database to use the same time zone consistently or come up with another scheme to discern timezone (e.g. store in a separate column).

For example: Your local time zone is GMT+2. You store "2012-12-25 10:00:00 UTC". The actual value stored in the database is "2012-12-25 12:00:00". You retrieve it again: you get it back again as "2012-12-25 10:00:00 UTC" (but only if you retrieve it using getTimestamp(..)), but when another application accesses the database in time zone GMT+0, it will retrieve the timestamp as "2012-12-25 12:00:00 UTC".

If you want to store it in a different timezone, then you need to use the setTimestamp(int parameterIndex, Timestamp x, Calendar cal) with a Calendar instance in the required timezone. Just make sure you also use the equivalent getter with the same time zone when retrieving values (if you use a TIMESTAMP without timezone information in your database).

So, assuming you want to store the actual GMT timezone, you need to use:

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
stmt.setTimestamp(11, tsSchedStartTime, cal);

With JDBC 4.2 a compliant driver should support java.time.LocalDateTime (and java.time.LocalTime) for TIMESTAMP (and TIME) through get/set/updateObject. The java.time.Local* classes are without time zones, so no conversion needs to be applied (although that might open a new set of problems if your code did assume a specific time zone).

That is:

  • replace getDate(..) with getObject(.., LocalDate.class)
  • replace setDate(.., dateValue) with setObject(.., localDateValue)
  • replace getTime(..) with getObject(.., LocalTime.class)
  • replace setTime(.., timeValue) with setObject(.., localTimeValue)
  • replace getTimestamp(..) with getObject(.., LocalDateTime.class)
  • replace setTimestamp(.., timestampValue) with setObject(.., localDateTimeValue)
2 of 8
41

I think the correct answer should be java.sql.Timestamp is NOT timezone specific. Timestamp is a composite of java.util.Date and a separate nanoseconds value. There is no timezone information in this class. Thus just as Date this class simply holds the number of milliseconds since January 1, 1970, 00:00:00 GMT + nanos.

In PreparedStatement.setTimestamp(int parameterIndex, Timestamp x, Calendar cal) Calendar is used by the driver to change the default timezone. But Timestamp still holds milliseconds in GMT.

API is unclear about how exactly JDBC driver is supposed to use Calendar. Providers seem to feel free about how to interpret it, e.g. last time I worked with MySQL 5.5 Calendar the driver simply ignored Calendar in both PreparedStatement.setTimestamp and ResultSet.getTimestamp.

Find elsewhere
🌐
Reddit
reddit.com › r/javahelp › is there a straightforward way to render instant timestamp into user’s local time zone?
r/javahelp on Reddit: Is there a straightforward way to render Instant timestamp into user’s local time zone?
October 12, 2022 -

So my application (android) uses Instant to log timestamped events. The events are printed to a csv file and being reviewed by a technologically-illiterate human being. The time is printed using Instant.toString() and it‘s in UTC. I want to render it to the user’s local time zone; the time zone can very.

So my thought process is to first get the user’s timezone using either ZoneOffset or ZoneID and then applying that offset to the Instant timestamp. But I am getting all sorts of confused with all the different possible classes to use from Java Time and their naming and all of that. Been going through a lot of SO posts and a lot of them use outdated/deprecated classes from before Java 8 Time and the ones that don’t, just confused me even more.

What’s the straightforward way of rendering the UTC Instant Timestamp to the user’s local time zone date and time? Is ZonedDateTime the class representation of what I’m looking for? How do I use ZoneOffset to convert the original timestamp to the local date and time?

Top answer
1 of 2
5
LocalDateTime.ofInstant(instant, ZoneId.systemDefault()) A user's timezone implies it's a local time, so you don't need to bother with ZonedDateTime or OffsetDateTime. EDIT: Pressed the button too soon. Added missing comment.
2 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Converting Between java.sql.Timestamp and ZonedDateTime in Java - Java Code Geeks
June 27, 2024 - The above code snippet retrieves the current time as a ZonedDateTime using the system’s default time-zone. It then converts this ZonedDateTime to an Instant and subsequently to milliseconds since the Unix epoch. Using these milliseconds, it initializes a DateTime object from the Joda-Time library. Next, it converts this DateTime object to a java.sql.Timestamp.
🌐
How to do in Java
howtodoinjava.com › home › java date time › get current timestamp in java
Get Current Timestamp in Java
April 4, 2023 - Timestamp timestamp1 = new Timestamp(System.currentTimeMillis()); Date date = new Date(); Timestamp timestamp2 = new Timestamp(date.getTime()); System.out.println(timestamp1); //2022-02-15 13:55:56.18 System.out.println(timestamp2); //2022-02-15 ...
Top answer
1 of 2
2

Your code using java.time classes:

        ZonedDateTime zdt = ZonedDateTime.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        DateTimeFormatter dfGMT = df.withZone(ZoneId.of("GMT"));
        
        String dateString = dfGMT.format(zdt);
        System.out.println("DateString: "+dateString);
        
        ZonedDateTime parsedDate = ZonedDateTime.parse(dateString,dfGMT);
        System.out.println("ParsedDate: "+ parsedDate);
        Timestamp timestamp = Timestamp.from(parsedDate.toInstant());
        System.out.println("Zoned Timestamp: "+timestamp);
        
        //ignoring zone info from date string
        LocalDateTime ldt = LocalDateTime.from(dfGMT.parse(dateString));
        timestamp = Timestamp.valueOf(ldt);
        System.out.println("Zone stripped GMT timestamp: "+timestamp);
        
        
        ZonedDateTime zdt1 = ldt.atZone(ZoneId.of("GMT"));
        zdt1 = zdt1.withZoneSameInstant(ZoneId.of("America/Chicago"));
        timestamp = Timestamp.valueOf(zdt1.toLocalDateTime());
        System.out.println("Zone stripped CST timestamp: "+timestamp);

Output:

DateString: 2021-03-26T09:10:37.537+0000
ParsedDate: 2021-03-26T09:10:37.537Z[GMT]
Zoned Timestamp: 2021-03-26 14:40:37.537
Zone stripped GMT timestamp: 2021-03-26 09:10:37.537
Zone stripped CST timestamp: 2021-03-26 04:10:37.537
2 of 2
0

java.time and JDBC 4.2

You don’t need any formatting, parsing nor conversion. To insert the current timestamp into your SQL database:

    OffsetDateTime currentTimestamp = OffsetDateTime.now(ZoneOffset.UTC);
    String sql = "insert into your_table(your_timestamp_with_time_zone_column) values (?);";
    try (PreparedStatement prepStmt = yourDatabaseConnection.prepareStatement(sql)) {
        prepStmt.setObject(1, currentTimestamp);
        prepStmt.executeUpdate();
    }
🌐
Baeldung
baeldung.com › home › java › java dates › get the current date and time in java
Get the Current Date and Time in Java | Baeldung
January 8, 2024 - We’ll start by covering the modern ... To get the date in any other timezone we can use LocalDate.now(ZoneId): LocalDate localDate = LocalDate.now(ZoneId.of("GMT+02:30")); We can also use java.time.LocalDateTime to get an instance ...
🌐
Quora
quora.com › How-do-I-get-the-date-and-time-of-a-specific-time-zone-in-Java
How to get the date and time of a specific time zone in Java - Quora
As a consequence, for number of milliseconds after epoch a Date must be specified first: use LocalDateTime, convert it to an instantaneous point on the time-line (Instant); specify time zone or time zone offset and use toEpochMilli to get the value.
🌐
Baeldung
baeldung.com › home › java › java dates › convert between java.time.instant and java.sql.timestamp
Convert Between java.time.Instant and java.sql.Timestamp | Baeldung
March 17, 2024 - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); formatter = formatter.withZone(TimeZone.getTimeZone("UTC").toZoneId()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); assertThat(formatter.format(instant)).isEqualTo(df.format(timestamp)); In this quick tutorial, we saw how to convert between java.time.Instant and java.sql.Timestamp classes in Java using built-in methods.
🌐
Epochconverter
epochconverter.io › blogs › java-timestamp-conversions
Java timestamp Conversions
For example, to use the timezone "America/Los_Angeles", you can use the following code: 1 2 3 4TimeZone timeZone = TimeZone.getTimeZone("America/Los_Angeles"); Calendar calendar = Calendar.getInstance(timeZone); long timestamp = calendar.getTimeInMillis(); System.out.println(timestamp);This will ...
🌐
Phrase
phrase.com › home › resources › blog › how to get the current utc date and time in java?
Solved: How to Get the Current UTC Date and Time in Java?
September 23, 2022 - In general, this isn’t ideal as it displays the current time based on the time zone of the specified region, which may be different than GMT; therefore, you should ideally avoid it. A better and more modern option bundled within the core Java library (and not using any third-party offerings) is to use the java.time package.
🌐
Coderanch
coderanch.com › t › 521562 › java › date-time-TimeZone
Get date and time using TimeZone. (Java in General forum at Coderanch)
. . I am trying to get the date and time at the specified TimeZone (Eastern Standard Time) but I am getting the system date and time. Am I making any mistake in the code? Please guide me. Thanks and regards, Nitin. ... The Three-letter time zone IDs are deprecated, therefore you are better of by using the long zone id - eg. "America/Los_Angeles". The TimeZone isn't been shown on a Date object, because it has no information on it - but it is stored on the Calendar object, therefore you need to use this information when you want to show the correct Date/Time by using SimpleDateFormat.
🌐
Medium
medium.com › @thilini_ › working-with-time-zones-and-time-in-software-development-248234771c05
Working with Local and Zoned Time in Java | by Thilini Fernando | Medium
June 17, 2022 - Java 8 introduces a new date-time API under the package java.time. Following are some of the important classes introduced in java.time package. Local − Simplified date-time API with no complexity of timezone handling.