Search code examples
javadatetimezoneutcgmt

How to convert UTC formatted string to calendar in specific timezone?


I'm trying to convert some string that is in UTC time to a java Calendar object that should be set to GMT-5.

My current UTC string input is this:

UTC date : 20050329174411

I use this code (I detect the 'pattern' as shown below):

DateFormat dateFormat = new SimpleDateFormat(pattern);
Date date = dateFormat.parse(utcDate);
calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-5"));
calendar.setTime(date);

I then printed the time like this:

calendar.getTime()

And I got this result:

GMT date : Tue Mar 29 17:44:11 EST 2005

I need to support theses date/time string patterns:

FORMAT_UTC4 = "yyyy";           
FORMAT_UTC6 = "yyyyMM";         
FORMAT_UTC8 = "yyyyMMdd";       
FORMAT_UTC10 = "yyyyMMddHH";    
FORMAT_UTC12 = "yyyyMMddHHmm";  
FORMAT_UTC14 = "yyyyMMddHHmmss";

I would be expecting the time to be set to "12:44:11". I have read a couple of examples and I find date time handling pretty confusing. For me, it's always the same, I get some sort of string formatted UTC and I convert it to GMT-5. I really feel it should be easy!

Ref 1 : How can I get the current date and time in UTC or GMT in Java?

Ref 2 : How to handle calendar TimeZones using Java?


Solution

  • You must set the SimpleDateFormat's time zone to UTC before parsing the date. Else, it uses your default timezone.

    And to display the date in the "GMT-5" timezone, you should use another DateFormat, with the timezone set to GMT-5, and format the date with this DateFormat. The toString() method of Date uses your default time zone to transform the date into something readable.