291

I have parsed a java.util.Date from a String but it is setting the local time zone as the time zone of the date object.

The time zone is not specified in the String from which Date is parsed. I want to set a specific time zone of the date object.

How can I do that?

2
  • 8
    While not really an answer to your question, I've used Joda Time after seeing it mentioned here a few times. It seems more rational to me than the standard APIs, and can do this sort of thing quite easily.
    – clstrfsck
    May 23, 2010 at 10:40
  • 3
    @msandiford Nowadays, use java.time classes rather than Joda-Time. The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle. Jan 18, 2018 at 19:49

11 Answers 11

366

Use DateFormat. For example,

SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = isoFormat.parse("2010-05-23T09:01:02");
6
  • 7
    if the date is created from Calendar class, you can set the timezone for Calendar.
    – Jackie
    Jan 11, 2013 at 3:07
  • 37
    @lwpro2 that statement is misleading; You can set the timezone for a Calendar object, but getting a Date object from it using the getTime() method will return a Date object with the host computer's time zone.
    – BrDaHa
    Dec 8, 2014 at 21:37
  • 2
    @BrDaHa is correct.You'll need to TimeZone.setDefault() before calling getTime() so that the new date object will be in the time zone that you want. In JDK 1.8, Calendar.getTime() calls return new Date(getTimeInMillis());.
    – jpllosa
    May 9, 2017 at 9:29
  • Warning at: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates.
    – Angel
    Sep 22, 2021 at 6:24
  • 1
    @Woodchuck is absolutely right.....
    – Chris W.
    Jun 10, 2023 at 17:31
228

Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.

As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.

10
  • 100
    After a Googling, experimenting and expleting, I've realised this is a precise and helpful addition to the answer - and worth highlighting: Date only contains the millisecond value. If you look at the source, there's pretty much just a long field called fastTime. Date.toString() actually uses a Calendar to interpret this millisecond time. So printing out a Date makes it appear to have a (default) timezone, leading to understandable questions about how to set that timezone. Jul 11, 2012 at 13:41
  • 4
    there IS timezone info inside the Date objects. But it might be true, you cannot change it.
    – Jackie
    Jan 11, 2013 at 3:09
  • 3
    @Iwpro2, Jesper claims (and I agree) that the Date object does not store a time zone. If you are claiming that the time zone is stored inside java.util.Date please provide a reference.
    – Jim
    Aug 20, 2013 at 19:57
  • 8
    @Jim, this is the source code for java.util.Date. It contains fastTime as unix epoch as well as BaseCalendar.Date cdate that is used in favor of fastTime, if it is defined. That one contains timezone information. I understand it so that a Date instance can contain timezone information, but it might not.
    – eis
    Sep 5, 2013 at 14:50
  • 2
    @Jim I didn't say you could set it, I was saying that it contains this information. I don't see any way of setting it as user either. I think OP is correct in that it seems to always be the user/system default timezone.
    – eis
    Sep 9, 2013 at 19:51
160

tl;dr

…parsed … from a String … time zone is not specified … I want to set a specific time zone

LocalDateTime.parse( "2018-01-23T01:23:45.123456789" )  // Parse string, lacking an offset-from-UTC and lacking a time zone, as a `LocalDateTime`.
    .atZone( ZoneId.of( "Africa/Tunis" ) )              // Assign the time zone for which you are certain this date-time was intended. Instantiates a `ZonedDateTime` object.

No Time Zone in j.u.Date

As the other correct answers stated, a java.util.Date has no time zone. It represents UTC/GMT (no time zone offset). Very confusing because its toString method applies the JVM's default time zone when generating a String representation.

Avoid j.u.Date

For this and many other reasons, you should avoid using the built-in java.util.Date & .Calendar & java.text.SimpleDateFormat. They are notoriously troublesome.

Instead use the java.time package bundled with Java 8.

java.time

The java.time classes can represent a moment on the timeline in three ways:

  • UTC (Instant)
  • With an offset (OffsetDateTime with ZoneOffset)
  • With a time zone (ZonedDateTime with ZoneId)

Instant

In java.time, the basic building block is Instant, a moment on the time line in UTC. Use Instant objects for much of your business logic.

Instant instant = Instant.now();

OffsetDateTime

Apply an offset-from-UTC to adjust into some locality’s wall-clock time.

Apply a ZoneOffset to get an OffsetDateTime.

ZoneOffset zoneOffset = ZoneOffset.of( "-04:00" );
OffsetDateTime odt = OffsetDateTime.ofInstant( instant , zoneOffset );

ZonedDateTime

Better is to apply a time zone, an offset plus the rules for handling anomalies such as Daylight Saving Time (DST).

Apply a ZoneId to an Instant to get a ZonedDateTime. Always specify a proper time zone name. Never use 3-4 abbreviations such as EST or IST that are neither unique nor standardized.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

LocalDateTime

If the input string lacked any indicator of offset or zone, parse as a LocalDateTime.

If you are certain of the intended time zone, assign a ZoneId to produce a ZonedDateTime. See code example above in tl;dr section at top.

Formatted Strings

Call the toString method on any of these three classes to generate a String representing the date-time value in standard ISO 8601 format. The ZonedDateTime class extends standard format by appending the name of the time zone in brackets.

String outputInstant = instant.toString(); // Ex: 2011-12-03T10:15:30Z
String outputOdt = odt.toString(); // Ex: 2007-12-03T10:15:30+01:00
String outputZdt = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]

For other formats use the DateTimeFormatter class. Generally best to let that class generate localized formats using the user’s expected human language and cultural norms. Or you can specify a particular format.


Table of all date-time types in Java, both modern and legacy


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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

While Joda-Time is still actively maintained, its makers have told us to migrate to java.time as soon as is convenient. I leave this section intact as a reference, but I suggest using the java.time section above instead.

In Joda-Time, a date-time object (DateTime) truly does know its assigned time zone. That means an offset from UTC and the rules and history of that time zone’s Daylight Saving Time (DST) and other such anomalies.

String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeIndia = new DateTime( input, timeZone );
DateTime dateTimeUtcGmt = dateTimeIndia.withZone( DateTimeZone.UTC );

Call the toString method to generate a String in ISO 8601 format.

String output = dateTimeIndia.toString();

Joda-Time also offers rich capabilities for generating all kinds of other String formats.

If required, you can convert from Joda-Time DateTime to a java.util.Date.

Java.util.Date date = dateTimeIndia.toDate();

Search StackOverflow for "joda date" to find many more examples, some quite detailed.


Actually there is a time zone embedded in a java.util.Date, used for some internal functions (see comments on this Answer). But this internal time zone is not exposed as a property, and cannot be set. This internal time zone is not the one used by the toString method in generating a string representation of the date-time value; instead the JVM’s current default time zone is applied on-the-fly. So, as shorthand, we often say “j.u.Date has no time zone”. Confusing? Yes. Yet another reason to avoid these tired old classes.

10
  • 3
    "No Time Zone in j.u.Date" is wrong. There is a timezone information in j.u.Date stored in its BaseCalendar.Date cdate property if set. Take a look at the source code here. You can't set the timezone of a j.u.Date object except by changing the default timezone of the JVM by calling TimeZone.setDefault(TimeZone.getTimeZone("NEW_TIME_ZONE"));. Thus, there is a timezone offset and you can get the offset by calling the deprecated method j.u.Date.getTimezoneOffset()
    – Thai Bui
    Jan 8, 2015 at 21:22
  • 5
    @blquythai Correct, you did your homework. As did I, having seen that source code before. There is a time zone buried in there. But for all practical purposes that time zone is ignored. A java.util.Date works without any time zone, in effect being in UTC, while ignoring that buried time zone. Except for the toString method which applies the JVM’s current default time zone; again ignoring the buried time zone. So for brevity, we say a java.util.Date has no time zone. Like Art, it's a lie that tells the truth. Jan 9, 2015 at 5:34
  • 1
    @blquythai As for calling TimeZone.setDefault, you are not setting the time zone of the java.util.Date object -- the Date object still ignores its buried time zone, acting effectively in UTC. You would affect Date’s toString method. Setting the default changes the JVM’s default time zone which is usually set to the host operating system’s time zone. That call is not recommended as it affects all the code in all the threads of all the apps running in that JVM, and does so on-the-fly as they are executing. Being rude and dangerous, that call should only be considered as a last resort. Jan 9, 2015 at 5:41
  • 5
    That time zone is used very often (used in equals, hashcode, getTime..) If you take a look at the equals method, it calls getTime() which calls getTimeImpl(), which calls normalize() if the cdate property is not normalized. In normalize() method, the last if condition re-calculates the milliseconds since 1/1/70 based on its stored timezone information if the timezone of cdate is different from the timezone of the current JVM environment it is running on. (Take a look at sun.util.calendar.AbstractCalendar getCalendarDate(long millis, CalendarDate date))
    – Thai Bui
    Jan 9, 2015 at 18:27
  • 3
    @MichalM Per your advice, some time ago I added an afterword about the embedded zone. Dec 22, 2017 at 18:10
84

You could also set the timezone at the JVM level

Date date1 = new Date();
System.out.println(date1);

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
// or pass in a command line arg: -Duser.timezone="UTC"

Date date2 = new Date();
System.out.println(date2);

output:

Thu Sep 05 10:11:12 EDT 2013
Thu Sep 05 14:11:12 UTC 2013
6
  • 1
    This helped me. setting timeZone in SDF didn't make any diff Dec 18, 2013 at 15:58
  • I think its more reliable. (+1)
    – foobar
    Dec 20, 2013 at 12:23
  • 28
    Beware: Calling TimeZone.setDefault is rather drastic, as it affects the entire JVM, affects all other objects and threads. See this answer for details including even more complications if you are running with a SecurityManager. Adding even more complication: This behavior has changed in various versions of Java, as discussed in this Question. Mar 2, 2014 at 10:53
  • This sets a common timezone across all threads spawned after this statement, right ?
    – Jaydev
    May 13, 2016 at 7:36
  • 1
    This is a better answer to the question than the accepted one.
    – user2587965
    Aug 16, 2018 at 14:30
12

If you must work with only standard JDK classes you can use this:

/**
 * Converts the given <code>date</code> from the <code>fromTimeZone</code> to the
 * <code>toTimeZone</code>.  Since java.util.Date has does not really store time zome
 * information, this actually converts the date to the date that it would be in the
 * other time zone.
 * @param date
 * @param fromTimeZone
 * @param toTimeZone
 * @return
 */
public static Date convertTimeZone(Date date, TimeZone fromTimeZone, TimeZone toTimeZone)
{
    long fromTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, fromTimeZone);
    long toTimeZoneOffset = getTimeZoneUTCAndDSTOffset(date, toTimeZone);

    return new Date(date.getTime() + (toTimeZoneOffset - fromTimeZoneOffset));
}

/**
 * Calculates the offset of the <code>timeZone</code> from UTC, factoring in any
 * additional offset due to the time zone being in daylight savings time as of
 * the given <code>date</code>.
 * @param date
 * @param timeZone
 * @return
 */
private static long getTimeZoneUTCAndDSTOffset(Date date, TimeZone timeZone)
{
    long timeZoneDSTOffset = 0;
    if(timeZone.inDaylightTime(date))
    {
        timeZoneDSTOffset = timeZone.getDSTSavings();
    }

    return timeZone.getRawOffset() + timeZoneDSTOffset;
}

Credit goes to this post.

1
  • 4
    The offset of timezones are not always constant. In fact, they may change due to geopolitical reasons. TimeZone.getDSTSavings() doesn't take this into account, and always returns the current offset. This means that you may get a wrong conversion in case you're dealing with a historical date with a fromTimeZone/toTimeZone that has changed offsets since that date.
    – andrerobot
    Nov 29, 2016 at 19:28
6

java.util.Calendar is the usual way to handle time zones using just JDK classes. Apache Commons has some further alternatives/utilities that may be helpful. Edit Spong's note reminded me that I've heard really good things about Joda-Time (though I haven't used it myself).

2
  • +1 for Joda Time. While it doesn't provide any additional functionality that you couldn't get from the standard Java API (that I've found in any case - happy to be shown otherwise), Joda Time does make some tasks easier. Feb 18, 2013 at 11:07
  • 2
    @JoshuaHutchison Joda-Time has tons of additional functionality. Example: Representing spans of time with the classes Period, Duration, and Interval. Those spans include comparison methods such as contains, abuts, overlap, and gap. And PeriodFormatterBuilder can build descriptive phrases such as "15 years and 8 months". Mar 2, 2014 at 10:32
1

Convert the Date to String and do it with SimpleDateFormat.

    SimpleDateFormat readFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    readFormat.setTimeZone(TimeZone.getTimeZone("GMT" + timezoneOffset));
    String dateStr = readFormat.format(date);
    SimpleDateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date date = writeFormat.parse(dateStr);
2
  • 1
    Answers on Stack Overflow are expected to have some discussion or explanation. This site is meant to be more than a code snippet library. Jan 17, 2018 at 16:38
  • thank you @Basil Bourque for your comment. I edit the answer
    – avisper
    Jan 18, 2018 at 19:34
1

This code was helpful in an app I'm working on:

    Instant date = null;
    Date sdf = null;
    String formatTemplate = "EEE MMM dd yyyy HH:mm:ss";
    try {
        SimpleDateFormat isoFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss");
        isoFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("US/Pacific")));
        sdf = isoFormat.parse(timeAtWhichToMakeAvailable);
        date = sdf.toInstant();

    } catch (Exception e) {
        System.out.println("did not parse: " + timeAtWhichToMakeAvailable);
    }

    LOGGER.info("timeAtWhichToMakeAvailable: " + timeAtWhichToMakeAvailable);
    LOGGER.info("sdf: " + sdf);
    LOGGER.info("parsed to: " + date);
1

Here you be able to get date like "2020-03-11T20:16:17" and return "11/Mar/2020 - 20:16"

 private String transformLocalDateTimeBrazillianUTC(String dateJson) throws  ParseException {
    String localDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";
    SimpleDateFormat formatInput = new SimpleDateFormat(localDateTimeFormat);

    //Here is will set the time zone
    formatInput.setTimeZone(TimeZone.getTimeZone("UTC-03"));

    String brazilianFormat = "dd/MMM/yyyy - HH:mm";
    SimpleDateFormat formatOutput = new SimpleDateFormat(brazilianFormat);
    Date date = formatInput.parse(dateJson);
    return formatOutput.format(date);
}
2
  • TimeZone.getTimeZone("UTC-03") yields GMT. I suspect that this is now what you thought. It’s not you. It’s the TImeZone class being troublesome. I recommend that we don’t use Date, SimpleDateFormat nor TimeZone. Instead use java.time as explained in the answer by Basil Bourque.
    – Anonymous
    Aug 21, 2020 at 3:04
  • On my computer your code gave 11/mar./2020 - 21:16. Note that the time is 21:16, it is wrong. I suggest LocalDateTime.parse("2020-03-11T20:16:17").atZone(ZoneId.of("America/Bahia")). It yields 2020-03-11T20:16:17-03:00[America/Bahia]. You may of course format it the way you want. Use a DateTimeFormatter for that.
    – Anonymous
    Aug 21, 2020 at 3:11
0

If anyone ever needs this, if you need to convert an XMLGregorianCalendar timezone to your current timezone from UTC, then all you need to do is set the timezone to 0, then call toGregorianCalendar() - it will stay the same timezone, but the Date knows how to convert it to yours, so you can get the data from there.

XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar(
        ((GregorianCalendar)GregorianCalendar.getInstance());
xmlStartTime.setTimezone(0);
GregorianCalendar startCalendar = xmlStartTime.toGregorianCalendar();
Date startDate = startCalendar.getTime();
XMLGregorianCalendar xmlStartTime = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar(startCalendar);
xmlStartTime.setHour(startDate.getHours());
xmlStartTime.setDay(startDate.getDate());
xmlStartTime.setMinute(startDate.getMinutes());
xmlStartTime.setMonth(startDate.getMonth()+1);
xmlStartTime.setTimezone(-startDate.getTimezoneOffset());
xmlStartTime.setSecond(startDate.getSeconds());
xmlStartTime.setYear(startDate.getYear() + 1900);
System.out.println(xmlStartTime.toString());

Result:

2015-08-26T12:02:27.183Z
2015-08-26T14:02:27.183+02:00
0
package org.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class time {
   public static void main(String[] args) {
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm");
       sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
       Date date=new Date();
       sdf.format(date);
       System.out.println(sdf.format(date));
   }
}
2
  • 1
    Thanks for wanting to contribute. I fail to see that this adds anything that isn’t already in the accepted answer and other answers? Also I strongly recommend you don’t use SimpleDateFormat and Date. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use ZonedDateTime, ZoneId and DateTimeFormatter, all from java.time, the modern Java date and time API.
    – Anonymous
    Jun 13, 2022 at 6:05
  • 1
    thanks for the reply i will check on this ZonedDateTime, ZoneId and DateTimeFormatter
    – akhesh
    Jun 16, 2022 at 13:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.