Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Jun 30, 2000

Converting Time Zones and Dates

The java.util.TimeZone class can be used to convert dates and times from local values (default) to other time zones. The following example shows how:
 
import java.util.*;
public class TimeZoneTest 
{
public static void main(java.lang.String[] args)
{
Arrays aTimeZones = null;
String[] sIds = TimeZone.getAvailableIDs(); // GET
ID'S
TimeZones.sort(sIds); // SORT ID'S
Calendar cal =
Calendar.getInstance(TimeZone.getDefault()); // CREATE
DEFAULT CALENDAR
displayDate(cal); // DISPLAY LOCAL TIME
for (int i = 0; i < sIds.length; i++)
{
cal.setTimeZone(TimeZone.getTimeZone(sIds[i]));
cal.setTime(cal.getTime()); // FORCE TIME RECALC
displayDate(cal); // DISPLAY TIME
}
}
// Format & display Calendar info
public static void displayDate(java.util.Calendar cal)
{
int iYear = cal.get(Calendar.YEAR);
int iMonth = cal.get(Calendar.MONTH);
int iDay = cal.get(Calendar.DAY_OF_MONTH);
int iHour = cal.get(Calendar.HOUR_OF_DAY);
int iMinute = cal.get(Calendar.MINUTE);
System.out.println(cal.getTimeZone().getID() + ": " +
buildTwoDigits(iMonth) + "/" + buildTwoDigits(iDay) +
"/" + iYear + " " + buildTwoDigits(iHour) + ":" +
buildTwoDigits(iMinute));
}
// Force two-digit display
public static  String buildTwoDigits(int iDigitIn)
{
String sDigitIn = Integer.toString(iDigitIn);
if (sDigitIn.length() == 1) return "0" + sDigitIn;
else return sDigitIn;
}
}
Note the following tips/traps:

* Calendar objects will inherit the local time zone by default. Calendar.getInstance() creates the same object as Calendar.getInstance(TimeZone.getDefault()). In addition, the local time will be set as the default value.

* Date objects will also inherit the local time zone value by default. Performing a getTime on a Calendar instance will return a Date value converted to the local time zone regardless of the time zone of the Calendar.
Timothy Carroll
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date