287

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?

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
Amit
  • 33,847
  • 91
  • 226
  • 299
  • 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 '10 at 10:40
  • 3
    @msandiford Nowadays, use *java.time* classes rather than Joda-Time. The [Joda-Time](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), with the team advising migration to the [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jan 18 '18 at 19:49

12 Answers12

365

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");
JJD
  • 50,076
  • 60
  • 203
  • 339
ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
  • 7
    if the date is created from Calendar class, you can set the timezone for Calendar. – Jackie Jan 11 '13 at 03:07
  • 36
    @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 08 '14 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 09 '17 at 09: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 '21 at 06:24
  • This answer seems to be of limited usefulness, as the resulting Date object appears to always be the host computer's time zone (as per @BrDaHa's comment above), regardless of what timezone you set for the SimpleDateFormat. – Woodchuck Feb 16 '23 at 20:08
  • 1
    @Woodchuck is absolutely right..... – Chris W. Jun 10 '23 at 17:31
223

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 96
    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. – David Carboni Jul 11 '12 at 13:41
  • 4
    there IS timezone info inside the Date objects. But it might be true, you cannot change it. – Jackie Jan 11 '13 at 03: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 '13 at 19:57
  • 8
    @Jim, [this](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Date.java) 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 05 '13 at 14:50
  • 1
    @eis Interesting. Where do you see that you can set the time zone of that internal cdate? As far as I can tell, it uses the user's default timezone, which sounds like the OPs problem. Also cdate is used with a bunch of the deprecated parts of Date, which seems like it would be better to stay away from. – Jim Sep 09 '13 at 19:20
  • 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 09 '13 at 19:51
  • It seems the only place where it mentions timezone is for the toString methods... using the user's time zone... It does contain a time zone by the way, the timezone is always UTC (Epoc is 1/1/1970 00:00:00 *UTC*, no?) – Eran Medan Feb 10 '15 at 00:13
  • when you say "number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC." Then you are saying TimeZone is UTC or GMT isnt it? – faisalbhagat Nov 10 '20 at 07:49
  • 1
    @faisalbhagat The only real information in a `java.util.Date` object is the number of milliseconds since a fixed point in time, which happens to be 01-01-1970, 00:00:00 UTC. The point is that you cannot change the timezone of a `Date` object. – Jesper Nov 11 '20 at 09:20
  • I know this is old, but I wanted to clarify, as this is something I have just been "fighting" with. tl;dr: all Dates have the same instance of ZoneInfo, which can be changed with TimeZone.setDefault(). java.util.Date **does** have a BaseCalendar.Date in it, which **does** have a ZoneInfo, which is used in the Date's toString() method. However, even if the BaseCalendar.Date is unique for each java.util.Date, the ZoneInfo is one and the same for every java.util.Date. If you change default TimeZone via TimeZone.setDefault(), it changes this ZoneInfo, and thus changes all Date's TimeZone. – Ray O'Kalahjan Jul 26 '21 at 12:30
155

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 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](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/util/Date.java). 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 08 '15 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](https://www.goodreads.com/quotes/67884-we-all-know-that-art-is-not-truth-art-is), it's a lie that tells the truth. – Basil Bourque Jan 09 '15 at 05: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. – Basil Bourque Jan 09 '15 at 05: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 09 '15 at 18:27
  • Well, we are engineers, not artists here (though many claim that programming is a form of art), so in my humble opinion it would be fair to at least leave a few words of disclaimer... No downvote, but in such a well and detailed answer I think it should be included. – Michal M Oct 14 '15 at 11:50
  • 3
    @MichalM Per your advice, some time ago I added an afterword about the embedded zone. – Basil Bourque Dec 22 '17 at 18:10
  • 1
    The answer is great, however there is something lacking from the Modern classes: They don't handle the Julian-Gregorian cutover, and if you use them with such early dates you will have errors. Any advice or suggestions? – Ariel Mar 02 '21 at 01:18
  • 1
    @Ariel There are thorny issues involved in historic date-time handling such as the Julian cutover and birth-of-Christ year zero. As a programmer working on business-oriented apps, I have little knowledge of, and little interest in, those issues. If one does care about those issues, be sure to read the documentation carefully to understand the design decisions made by the *java.time* authors. For contemporary usage, the *java.time* classes certainly work very well, leading the industry as far as I know. – Basil Bourque Mar 02 '21 at 02:26
  • @Ariel You may be interested in this alternate chronology implementation that you can plug into the *java.time* framework: [`org.threeten.extra.chrono.JulianChronology`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/chrono/JulianChronology.html). This chronology defines the rules of the proleptic Julian calendar system, forerunner to the modern Gregorian and ISO calendars. This class comes in the [*ThreeTen-Extra*](https://www.threeten.org/threeten-extra/) library. – Basil Bourque Jul 15 '21 at 21:03
  • I appreciated this _j.u.Date_ detail very much, and just want to add emphasis to it here: [`java.util.Date` is] **"Very confusing because its toString method applies the JVM's default time zone"**! (and of course, a JVM is running on some physical machine, which is physically located somewhere in the world in some time zone!) – cellepo Aug 26 '21 at 02:14
83

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
JJD
  • 50,076
  • 60
  • 203
  • 339
starmer
  • 2,197
  • 19
  • 12
  • 1
    This helped me. setting timeZone in SDF didn't make any diff – vishnu viswanath Dec 18 '13 at 15:58
  • I think its more reliable. (+1) – foobar Dec 20 '13 at 12:23
  • 27
    Beware: Calling `TimeZone.setDefault` is rather drastic, as it affects the entire JVM, affects all other objects and threads. See [this answer](http://stackoverflow.com/a/9891971/642706) 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](http://stackoverflow.com/q/2176784/642706). – Basil Bourque Mar 02 '14 at 10:53
  • This sets a common timezone across all threads spawned after this statement, right ? – Jaydev May 13 '16 at 07:36
  • 1
    This is a better answer to the question than the accepted one. –  Aug 16 '18 at 14:30
  • @francogrex I beg to differ. Setting the default time zone, potentially disturbing time operations anywhere in your program and in other programs running in the JVM, is not encouraged. Neither is using `Date` nor `TimeZone`, two poorly designed and outdated classes. – Ole V.V. Jul 14 '21 at 17:34
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.

diadyne
  • 4,038
  • 36
  • 28
  • 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 '16 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).

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • +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. – Joshua Hutchison Feb 18 '13 at 11:07
  • 2
    @JoshuaHutchison Joda-Time has *tons* of additional functionality. Example: Representing spans of time with the classes `Period`, `Duration`, and [`Interval`](http://www.joda.org/joda-time/apidocs/org/joda/time/Interval.html). Those spans include comparison methods such as `contains`, `abuts`, `overlap`, and `gap`. And [`PeriodFormatterBuilder`](http://www.joda.org/joda-time/apidocs/org/joda/time/format/PeriodFormatterBuilder.html) can build descriptive phrases such as "15 years and 8 months". – Basil Bourque Mar 02 '14 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);
avisper
  • 878
  • 12
  • 11
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);
VikR
  • 4,818
  • 8
  • 51
  • 96
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);
}
Bruno Camargos
  • 189
  • 1
  • 5
  • `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](https://stackoverflow.com/a/22126586/5772882). – Ole V.V. Aug 21 '20 at 03: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. – Ole V.V. Aug 21 '20 at 03: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
JJD
  • 50,076
  • 60
  • 203
  • 339
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
0

This answer is probably the shortest and it uses only the Date class:

long current = new Date().getTime() + 3_600_000;              //e.g. your JVM time zone +1 hour (3600000 milliseconds)
System.out.printf("%1$td.%1$tm.%1$tY %1$tH:%1$tM\n", current);//european time format

But, if you can, use more modern ways to doing the same.

antaki93
  • 704
  • 7
  • 10
  • 1
    But it’s wrong. It’s fake. You are formatting a different point in time to make it *look like* it’s in a different time zone than it is. – Ole V.V. Jul 14 '21 at 16:25
  • *But, if you can, use more modern ways to doing the same.* I very strongly agree. And you can. If you don’t have an evil boss forcing you to use Java 1.4 or earlier, you can. It’s all in [the good answer by Basil Bourque](https://stackoverflow.com/a/22126586/5772882). – Ole V.V. Jul 15 '21 at 06:26
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));
   }
}
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
akhesh
  • 1
  • 1
  • 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](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 13 '22 at 06:05
  • 1
    thanks for the reply i will check on this ZonedDateTime, ZoneId and DateTimeFormatter – akhesh Jun 16 '22 at 13:35