Translate

mercredi 1 mai 2013

TimeZone : let your application adapt Dates & Times to user's TimeZone


When we develop an application which communicates with web services and uses Date and Time, we have to adapt these informations to the users' Time Zone.
 
This simple example shows how to convert Date and Time from an input Time Zone to that of the user's device.
We will use Calendar class to get the user’s Time Zone and DateFormat class to convert our input Date and Time to the new Time Zone.

If you have your input Date-Time as a String, you can use the method parse of the DateFormat class to create a Date object from your String. You have to specify how your String is formatted.

Let’s get an example:
We need two methods:
  • getDateFromString: Convert ab input datetime String to Date object
  • ChangeTimeZonr: Covert DateTime from time zone 1 to phone time zone


public Date getDateFromString(String inputDateTime) { // Input date: you have
                                                      // to specify the
                                                      // time zone of the
                                                      // input date
DateFormat formater = new SimpleDateFormat(DATE_FORMAT);
       Date inputDate = null;
       try {
              inputDate = formater.parse(inputDateTime);
       } catch (ParseException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
       }
       return inputDate;
}


public String ChangeTimeZone(Date inputeDateTime) {
// output date specification of the format of the date
DateFormat formater = new SimpleDateFormat(OUTPUT_DATE_FORMAT);
// get an instance of the user calendar
       Calendar calendar = Calendar.getInstance();
       // get the user's timezone
       String timezone = calendar.getTimeZone().getID();
       // change the date to the user's timezone date
       formater.setTimeZone(TimeZone.getTimeZone(timezone));
       String newDateTime = formater.format(inputeDateTime);
       return newDateTime;
}

Here the code source of the example.
Find here how to get time zone list.

Aucun commentaire:

Enregistrer un commentaire