Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Application Security Testing: An Integral Part of DevOps

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
TimeZones.sort(sIds); // SORT ID'S
Calendar cal =
Calendar.getInstance(TimeZone.getDefault()); // CREATE
displayDate(cal); // DISPLAY LOCAL TIME
for (int i = 0; i < sIds.length; 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) + ":" +
// 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.



We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date