Categories
datetime formatting java timestamp timezone

Convert Date/Time for given Timezone – java

89

I want to convert this GMT time stamp to GMT+13:

2011-10-06 03:35:05

I have tried about 100 different combinations of DateFormat, TimeZone, Date, GregorianCalendar etc. to try to do this VERY basic task.

This code does what I want for the CURRENT TIME:

Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");    
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));  

String newZealandTime = formatter.format(calendar.getTime());

But what I want is to set the time rather than using the current time.

I found that anytime I try to set the time like this:

calendar.setTime(new Date(1317816735000L));

the local machine’s TimeZone is used. Why is that? I know that when “new Date()” returns UTC+0 time so why when you set the Time in milliseconds does it no longer assume the time is in UTC?

Is it possible to:

  1. Set the time on an object (Calendar/Date/TimeStamp)
  2. (Possibly) Set the TimeZone of the initial time stamp (calendar.setTimeZone(…))
  3. Format the time stamp with a new TimeZone (formatter.setTimeZone(…)))
  4. Return a string with new time zone time. (formatter.format(calendar.getTime()))

4

  • Too many questions in one post…

    – Barmaley

    Oct 6, 2011 at 4:59

  • Same 2 questions asked just the 2nd one is asked a second time with a scenario algorithm for clarity. Thanks for input tho 😕

    – travega

    Oct 6, 2011 at 11:10


  • Seems like the only problem is that 1317816735000L is the wrong timestamp for 2011-10-06 03:35:05 GMT. Otherwise your approach is correct.

    – augurar

    Apr 16, 2016 at 9:37


  • 1

    FYI, the troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

    Jun 29, 2018 at 19:43

76

For me, the simplest way to do that is:

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

Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

//Here you say to java the initial timezone. This is the secret
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//Will print in UTC
System.out.println(sdf.format(calendar.getTime()));    

//Here you set to your timezone
sdf.setTimeZone(TimeZone.getDefault());
//Will print on your default Timezone
System.out.println(sdf.format(calendar.getTime()));

7

  • 1

    @Charleston What is the review in line date = sdf.parse(review);

    Aug 27, 2015 at 9:40

  • 1

    @Charleston But there is no such method type in SDF, sdf.parse(DateObject) is not defined in java i am using JDK.1.7.

    Aug 31, 2015 at 6:55

  • I feel so sorry about my second answer. I don’t even tested it! But now Its tested and working!

    Sep 3, 2015 at 20:34

  • 3

    How do you get an actual Date instead of a String?

    May 2, 2016 at 19:52

  • 1

    Maybe it should be: SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”)

    – Marcos

    Sep 13, 2016 at 6:57

31

Understanding how computer time works is very important. With that said I agree that if an API is created to help you process computer time like real time then it should work in such a way that allows you to treat it like real time. For the most part this is the case but there are some major oversights which do need attention.

Anyway I digress!! If you have your UTC offset (better to work in UTC than GMT offsets) you can calculate the time in milliseconds and add that to your timestamp. Note that an SQL Timestamp may vary from a Java timestamp as the way the elapse from the epoch is calculated is not always the same – dependant on database technologies and also operating systems.

I would advise you to use System.currentTimeMillis() as your time stamps as these can be processed more consistently in java without worrying about converting SQL Timestamps to java Date objects etc.

To calculate your offset you can try something like this:

Long gmtTime =1317951113613L; // 2.32pm NZDT
Long timezoneAlteredTime = 0L;

if (offset != 0L) {
    int multiplier = (offset*60)*(60*1000);
    timezoneAlteredTime = gmtTime + multiplier;
} else {
    timezoneAlteredTime = gmtTime;
}

Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(timezoneAlteredTime);

DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

formatter.setCalendar(calendar);
formatter.setTimeZone(TimeZone.getTimeZone(timeZone));

String newZealandTime = formatter.format(calendar.getTime());

I hope this is helpful!

4

  • @user726478 Is this correct when we know timezone string? long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone(“Asia/Calcutta”).getRawOffset();”

    Nov 20, 2012 at 11:00


  • 4

    Not good. Time zone offset is not constant. It depends on actual date.

    Jul 29, 2015 at 13:53

  • 5

    How do you get an actual Date instead of a String?

    May 2, 2016 at 19:51

  • @KanagaveluSugumar here offset is hours

    – M.Y.

    Jun 8, 2017 at 11:24

26

As always, I recommend reading this article about date and time in Java so that you understand it.

The basic idea is that ‘under the hood’ everything is done in UTC milliseconds since the epoch. This means it is easiest if you operate without using time zones at all, with the exception of String formatting for the user.

Therefore I would skip most of the steps you have suggested.

  1. Set the time on an object (Date, Calendar etc).
  2. Set the time zone on a formatter object.
  3. Return a String from the formatter.

Alternatively, you can use Joda time. I have heard it is a much more intuitive datetime API.

4

  • Hi Bringer128 thanks for your reply it just seems ridiculous to me that there is no straight forward way to adjust a timestamp for a given timezone. Why include the functionality if all it does is alters the timezone tag in the formatted string… I will try Joda time. Thanks

    – travega

    Oct 6, 2011 at 20:12

  • @travega There is a simple way, if you represent your time as UTC and format it with a SimpleDateFormat. It is not just the ‘Z’ part (the timezone tag) that gets modified, the whole date does. Check the results of having two different SimpleDateFormat objects with different TimeZones set when they format the same date.

    – user545680

    Oct 7, 2011 at 3:04

  • How do you get an actual Date instead of a String?

    May 2, 2016 at 19:52

  • @TulainsCórdova I think you will need to explain in more detail. Can you create a question or search to find a related question that might solve your specific question?

    – user545680

    May 10, 2016 at 3:07