|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Using the Calendar Class to Display Current Time in Different Time Zones
To display time in a specific time zone we can use the Calendar class. After it has been created we set the time zone on the instance using the method setTimeZone. It is really all that is to it, after that we can just query the instance for hours and minutes as in the code example below where time in three major cities around the world is displayed. |
package com.javadb.examples; import java.util.Calendar; import java.util.TimeZone; /** * * @author www.javadb.com */ public class Main { public void setTimeZones() { Calendar calNewYork = Calendar.getInstance(); Calendar calParis = Calendar.getInstance(); Calendar calTokyo = Calendar.getInstance(); calNewYork.setTimeZone(TimeZone.getTimeZone("America/New_York")); calParis.setTimeZone(TimeZone.getTimeZone("Europe/Paris")); calTokyo.setTimeZone(TimeZone.getTimeZone("Asia/Tokyo")); System.out.println("Time in New York: " + calNewYork.get(Calendar.HOUR_OF_DAY) + ":" + calNewYork.get(Calendar.MINUTE)); System.out.println("Time in Paris: " + calParis.get(Calendar.HOUR_OF_DAY) + ":" + calParis.get(Calendar.MINUTE)); System.out.println("Time in Tokyo: " + calTokyo.get(Calendar.HOUR_OF_DAY) + ":" + calTokyo.get(Calendar.MINUTE)); } public static void main(String[] args) { Main main = new Main(); main.setTimeZones(); } } |
Here is what the output looked like when the example above was run: |
Time in New York: 13:52 Time in Paris: 19:52 Time in Tokyo: 2:52 |
To display a list of available time zone IDs, please see this link: |
Display Available Time Zones |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
