Java, GregorianCalendar from SimpleDateFormat, avoid conversion to local time zone

1.1k views Asked by At

I have to parse something like the string dep but I have no way to know in advance the time zone and the offset. I would like to parse the string, retrieve time zone and offset from the GregoriaCalendar instantiated object or avoid the conversion to the local time zone as happens running the following code:

public class Prova {
public static void main(String[] args) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy z");     
    String dep = "13/11/2014 GMT+08:00";
    GregorianCalendar gc1 = new GregorianCalendar();

    try {

        gc1.setTime(dateFormat.parse(dep));
        System.out.println( dateFormat.format(gc1.getTime()) + " time zone: " + gc1.getTimeZone().getID());

    } catch (ParseException | DatatypeConfigurationException e) {
        e.printStackTrace();
    }

}

}

The output is:

12/11/2014 CET time zone: Europe/Rome

I searched in Date, TimeZone, SimpleTimeZone class documentation but I did not find anything useful for my purpose. Thank you in advance!

1

There are 1 answers

0
markspace On BEST ANSWER

Here's what I came up with. Note the changes (commented lines). I also changed the date itself to be a positive offset from my time zone so I could reproduce your original error.

Basically I don't see anyway to do this except to treat the time and the time zone separately. You have to set each one or the Date object you create is going to convert to milliseconds, and it has no time zone.

class Prova
{

   public static void main( String[] args )
   {

//      SimpleDateFormat dateFormat = new SimpleDateFormat( 
//              "dd/MM/yyyy z" );
      SimpleDateFormat dateFormat = new SimpleDateFormat( 
              "dd/MM/yyyy" );
      String dep = "13/11/2014 GMT+12:00";
      GregorianCalendar gc1 = new GregorianCalendar();

      try {

         String[] dateZone = dep.split( " " );
         Date date = dateFormat.parse( dateZone[0] );
         TimeZone tz = TimeZone.getTimeZone( dateZone[1] );
         gc1.setTimeZone(tz);
         gc1.setTime(date);

//         gc1.setTime( dateFormat.parse( dep ) );
         System.out.println( dateFormat.format( gc1.getTime() ) +
                 " time zone: " + gc1.getTimeZone().getID() );

      } catch( ParseException e ) {
         e.printStackTrace();
      }

   }
}