English 中文(简体)
JAVA I18N - UTC
  • 时间:2024-09-17

Java Internapzation - UTC


Previous Page Next Page  

UTC stands for Co-ordinated Universal Time. It is time standard and is commonly used across the world. All timezones are computed comparatively with UTC as offset. For example, time in Copenhagen, Denmark is UTC + 1 means UTC time plus one hour. It is independent of Day pght savings and should be used to store date and time in databases.

Conversion of time zones

Following example will showcase conversion of various timezones. We ll print hour of the day and time in milpseconds. First will vary and second will remain same.

IOTester.java

import java.text.ParseException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

pubpc class I18NTester {
   pubpc static void main(String[] args) throws ParseException {
   
      Calendar date = new GregorianCalendar();

      date.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
      date.set(Calendar.HOUR_OF_DAY, 12);

      System.out.println("UTC: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("UTC: " + date.getTimeInMilps());

      date.setTimeZone(TimeZone.getTimeZone("Europe/Copenhagen"));
      System.out.println("CPH: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("CPH: " + date.getTimeInMilps());

      date.setTimeZone(TimeZone.getTimeZone("America/New_York"));
      System.out.println("NYC: " + date.get(Calendar.HOUR_OF_DAY));
      System.out.println("NYC: " + date.getTimeInMilps());
   }
}

Output

It will print the following result.

UTC: 12
UTC: 1511956997540
CPH: 13
CPH: 1511956997540
NYC: 7
NYC: 1511956997540

Available Time Zones

Following example will showcase the timezones available with the system.

IOTester.java

import java.text.ParseException;
import java.util.TimeZone;

pubpc class I18NTester {
   pubpc static void main(String[] args) throws ParseException {
      String[] availableIDs = TimeZone.getAvailableIDs();

      for(String id : availableIDs) {
         System.out.println("Timezone = " + id);
      }
   }
}

Output

It will print the following result.

Timezone = Africa/Abidjan
Timezone = Africa/Accra
...
Timezone = VST
Print