Clase Java.util.TimeZone | Serie 1

La clase TimeZone se usa para representar un desplazamiento de zona horaria y también calcula el horario de verano.
¿Qué es una zona horaria y un desfase horario?
“Zona horaria” se utiliza para describir la hora actual de diferentes áreas del mundo. Se refiere a una de las regiones específicas de las 24 regiones totales del mundo que se dividen por longitud. Dentro de cada una de esas regiones se mantiene una versión estándar de la hora. 
 

  • Los diferentes husos horarios se calculan en función de su relación con el tiempo universal coordinado o UTC.
  • Una compensación horaria es una cantidad de tiempo que se resta o se suma a la hora universal para obtener la hora civil actual, ya sea la hora estándar o el horario de verano (DST).
  • Dividimos toda la tierra de este a oeste en 24 regiones diferentes según la longitud, por lo que cada región es 15 grados más ancha. Entonces, hay 24 zonas horarias diferentes disponibles en la tierra. Cada zona horaria tiene 15 grados de ancho y hay una diferencia de una hora entre cada una.
  • Según la distancia al este o al oeste del meridiano de Greenwich, debe sumar o restar el tiempo apropiado para cada intervalo de 15 grados de longitud.

Por ejemplo: para encontrar la zona horaria en horas de una ubicación en particular, puede tomar la longitud en grados y dividirla entre 15. Entonces, por ejemplo, 105° E sería 105/15, lo que equivale a 7. Eso se traduce en la hora la zona está 7 horas por delante de la hora UTC o GMT, que también se puede etiquetar como UTC+7. Donde 7 es un desplazamiento de tiempo para esa ubicación.
 

Clase de zona horaria en Java

declaración de clase 

public abstract class TimeZone extends 
Object implements Serializable, Cloneable

Métodos de la clase TimeZone: 

  • getAvailableIDs() : con este método, puede obtener todas las ID de zona horaria disponibles. 
Syntax : public static String[] getAvailableIDs()
  • getAvailableIDs (int rawOffset) : con este método, puede obtener una array de ID, donde la zona horaria para esa ID tiene el desplazamiento GMT especificado en milisegundos. 
Syntax : public static String[] getAvailableIDs(int rawOffset)
Parameters: rawOffset - the given time zone GMT offset in milliseconds.

Java

// Java program for Demonstration of
// getAvailableIDs() and
// getAvailableIDs(int rawOffset ) methods
import java.util.TimeZone;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
 
        // get all the  timezones ids defined by TimeZone class
        String[] availableTimezones = TimeZone.getAvailableIDs();
 
        // Print Total no of TimeZones
        System.out.println("Total No of Time Zone Available");
 
        System.out.println(availableTimezones.length);
 
        // get all the  timezones  whose offset is
        // 7200000 milliseconds means 2 hour
        String[] timezones = TimeZone.getAvailableIDs(7200000);
 
        // Print Total no of TimeZones
        System.out.println("No of Time Zone having time offset 2 hour");
 
        System.out.println(timezones.length);
 
        // print all timezones names
        System.out.println("Timezone names having time offset 2 hour");
 
        for (int i = 0; i < timezones.length; i++)
            System.out.println(timezones[i]);
    }
}
Output:  
Total No of Time Zone Available
628
No of Time Zone having a time offset 2 hour
43
Timezone names having a time offset 2 hour
ART
Africa/Blantyre
Africa/Bujumbura
Africa/Cairo......
............
  • getDefault() : con este método, puede obtener la zona horaria del lugar donde se ejecuta el programa. 
Syntax : public static TimeZone getDefault()
  • getDisplayName() : el método devuelve un nombre de hora estándar largo de initialize TimeZone. 
Syntax : public final String getDisplayName() 

Java

// Java program for Demonstration of
// getDefault() and getDisplayName() methods
import java.util.TimeZone;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
 
        // Get your Local Time Zone Where this Program is Running.
        TimeZone timezone = TimeZone.getDefault();
 
        // Get the Name of Time Zone
        String LocalTimeZoneDisplayName = timezone.getDisplayName();
 
        // Print the Name of Time Zone
        System.out.println(LocalTimeZoneDisplayName);
    }
}
Output:  
Coordinated Universal Time
  • getTimeZone(String ID) – Este método se usa para obtener la zona horaria para la ID dada. 
Syntax :public static TimeZone getTimeZone(String ID)
Parameters: ID - the ID for a TimeZone.
  • getDSTSavings() : el método devuelve la cantidad de tiempo que se agregará a la hora estándar local para obtener la hora del reloj de pared local. 
Syntax : public int getDSTSavings()
  • getID() : este método se usa para obtener la identificación de esta zona horaria. 
Syntax : public String getID()

Java

// Java program for Demonstration of
// getTimeZone(String ID),
// getDSTSavings()  and getID() methods
import java.sql.Time;
import java.util.TimeZone;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
 
        // creating Timezone object whose id is Europe/Berlin
        TimeZone timezone = TimeZone.getTimeZone("Europe/Berlin");
 
        // printing the Display Name of this timezone object
        System.out.println("Display Name");
 
        System.out.println(timezone.getDisplayName());
 
        // getting DST in milliseconds
        int timeInMilliseconds = timezone.getDSTSavings();
 
        System.out.println("\nDST of Europe/Berlin is");
        System.out.println(timezone.getDSTSavings());
 
        // get Id of your Default Time Zone
        TimeZone defaultTimezone = TimeZone.getDefault();
 
        System.out.println("\nThe id of default Time zone is");
        System.out.println(timezone.getID());
    }
}
Output: 
Display Name
Central European Time

DST of Europe/Berlin is
3600000

The id of default Time zone is
Europe/Berlin
  • getOffset (fecha larga) : el método se usa para devolver el desplazamiento de esta zona horaria desde UTC en la fecha pasada en el método. 
Syntax : the method is used to return the offset of this time zone
 from UTC at the passed date in method.
Parameters: date - the date represented in milliseconds
 since January 1, 1970 00:00:00 GMT
  • inDaylightTime(Date date) : este método devuelve verdadero si la fecha dada está en el horario de verano en esta zona horaria, de lo contrario, es falso. 
Syntax :Syntax : public abstract boolean inDaylightTime(Date date)
Parameters:date - the given Date.
  • observaDaylightTime() : este método devuelve verdadero si esta zona horaria se encuentra actualmente en el horario de verano, o si se produce una transición del horario estándar al horario de verano en cualquier momento futuro. 
Syntax :public boolean observesDaylightTime()

Java

// Java program for
// Demonstration of getOffset(long date),
// inDaylightTime(Date date)  and
// observesDaylightTime() methods
import java.sql.Time;
import java.util.*;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
 
        // creating Timezone object whose id is Europe/Berlin
        TimeZone timezone = TimeZone.getTimeZone("Europe/Berlin");
 
        // printing offset value
        System.out.println("Offset value of Europe/Berlin:");
 
        System.out.println(timezone.getOffset(Calendar.ZONE_OFFSET));
 
        // create Date Object
        Date date = new Date(2017, 04, 16);
 
        // checking the date is in day light time of that Time Zone or not
        System.out.println("\nDate 16/04/2017 is in Day Light Time of");
 
        System.out.println("Timezone: timezone.getDisplayName()");
        System.out.println(timezone.inDaylightTime(date));
 
        // check this Time Zone observes Day Light Time or Not
        System.out.println("\nTimeZone name " + timezone.getDisplayName());
 
        System.out.println("Observes Day Light Time");
        System.out.println(timezone.observesDaylightTime());
    }
}
Output:
Offset value of Europe/Berlin:
3600000

Date 16/04/2017 is in Day Light Time of
Timezone: timezone.getDisplayName()
true

TimeZone name Central European Time
Observes Day Light Time
true
  • setDefault(TimeZone zone) : se utiliza para establecer la zona horaria que devuelve el método getDefault. 
Syntax : public static void setDefault(TimeZone zone)
Parameters: zone - the new default time zone
  • setID (ID de string) : se utiliza para configurar la ID de la zona horaria. 
Syntax :public void setID(String ID)
Parameters: ID - the new time zone ID.
  • clone() : este método se usa para crear una copia de esta zona horaria 
Syntax : public Object clone()

Java

// Java program for Demonstration of
// setDefault(TimeZone zone),
// setID(String ID)  and clone() methods
import java.util.*;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
 
        // My previous Default Time Zone is
        TimeZone DefaultTimeZone = TimeZone.getDefault();
 
        System.out.println("Current Default TimeZone:");
        System.out.println(DefaultTimeZone.getDisplayName());
 
        // Setting  Europe/Berlin as your Default Time Zone
        TimeZone timezone = TimeZone.getTimeZone("Europe/Berlin");
 
        timezone.setDefault(timezone);
        TimeZone NewDefaultTimeZone = TimeZone.getDefault();
        System.out.println("\nNew Default TimeZone:");
        System.out.println(NewDefaultTimeZone.getDisplayName());
 
        // change Id Europe/Berlin to Eur/Ber
        timezone.setID("Eur/Ber");
 
        System.out.println("\nNew Id of Europe/Berlin is");
        System.out.println(timezone.getID());
 
        // create copy of a time zone
        System.out.println("\nOriginal TimeZone ID:");
 
        System.out.println(timezone.getID());
        TimeZone clonedTimezone = (TimeZone)timezone.clone();
        System.out.println("Cloned TimeZone ID:");
        System.out.println(clonedTimezone.getID());
    }
}
Output:
Current Default TimeZone:
India Standard Time

New Default TimeZone:
Central European Time

New Id of Europe/Berlin is
Eur/Ber

Original TimeZone ID:
Eur/Ber
Cloned TimeZone ID:
Eur/Ber

Ejemplo: Imprima la fecha y la hora para cualquier zona horaria de entrada dada donde se ejecuta el programa. 

Java

// Java program to illustrate
// java.util.timezone class
import java.text.*;
import java.util.*;
 
public class TimeZoneDemo {
 
    public static void main(String[] args)
    {
        // Get your Local Time Zone Where this Program is Running.
        TimeZone timezone = TimeZone.getDefault();
 
        // Get the Name of Time Zone
        String LocalTimeZoneName = timezone.getDisplayName();
 
        // Initialize your Date Object and Date Format to represent your Date
        Date date = new Date();
        DateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        // set your local time Zone to your Date Format time Zone
        dformat.setTimeZone(timezone);
 
        // Print Date and Time for your Time Zone
        System.out.println("Date and time of your Local Time Zone:");
        System.out.println(LocalTimeZoneName + ", " + dformat.format(date));
    }
}
 Output:  
Date and time of your Local Time Zone:
Coordinated Universal Time, 2018-04-17 07:36:19

Referencia: documentación de Oracle

Publicación traducida automáticamente

Artículo escrito por AmanSingh2210 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *