Search code examples
javatimezoneutcdate-formatsimpledateformat

Java TimeZone conversions


I understand that java Date is timezoneless and trying to set different timezone on Java Calendar wouldn't convert date to an appropriate Time Zone. So I have tried following code

 public static String DATE_FORMAT="dd MMM yyyy hh:mm:ss";
 public static String CURRENT_DATE_STRING ="31 October 2011 14:19:56 GMT";
 DateFormat dateFormat =  new SimpleDateFormat(DATE_FORMAT);
 dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
 System.out.println(dateFormat.parseObject(CURRENT_DATE_STRING));

but it outputs wrong date Mon Oct 31 16:19:56 when it must be 12:19:56?


Solution

  • The main issue here is your date format string is using hh (12-hour clock) instead of HH (24-hour)

    Secondly, your date format should specify that your date string contains the timezone. (Alternatively you could uncomment the commented line, to tell it the correct timezone).

    Thirdly, you should use a DateFormat to output the time to screen aswell...

    Finally, UTC = GMT, so the UTC time is also 14:19:56

    (GMT, 'British Winter Time', is the same as UTC, whereas BST is one hour ahead)

    public class DateFormatTest {
        public static String DATE_FORMAT="dd MMM yyyy HH:mm:ss z";
         public static String CURRENT_DATE_STRING ="31 October 2011 14:19:56 GMT";
    
        public static void main(String[] args) throws ParseException {
             DateFormat dateFormat =  new SimpleDateFormat(DATE_FORMAT);
             //dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
             Date d= dateFormat.parse(CURRENT_DATE_STRING);
             dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
             System.out.println(dateFormat.format(d));
        }
    }
    

    Output: 31 Oct 2011 14:19:56 UTC

    HTH