Introducción al tipo de fecha - 1

"Hola, amigo. Quiero contarte sobre un tipo interesante llamado Fecha. Este tipo almacena la fecha y la hora, y también puede medir intervalos de tiempo".

"Suena interesante. Por favor, continúa".

"Cada objeto Date almacena una hora en una forma bastante interesante: la cantidad de milisegundos desde el 1 de enero de 1970, GMT".

"¡Vaya!"

"Sí. Este número es tan grande que no hay espacio suficiente para él en un int , por lo que debe almacenarse en un long . Pero es realmente útil para calcular la diferencia entre dos fechas cualesquiera. Solo haces una resta para encontrar la diferencia con precisión al milisegundo. También resuelve el problema de la línea de fecha y el horario de verano".

"La parte más interesante es que cada objeto se inicializa con la hora actual en su creación. Para saber la hora actual, solo necesita crear un objeto Fecha".

"¿Cómo trabajas con eso?"

"Aquí hay unos ejemplos:"

Obtener la fecha actual:
public static void main(String[] args) throws Exception
{
     Date today = new Date();
     System.out.println("Current date: " + today);
}
Calcular la diferencia entre las dos fechas.
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();           // Get the current date and time
    Thread.sleep(3000);                      // Wait 3 seconds (3000 milliseconds)
    Date newTime = new Date();               // Get the new current time

    long msDelay = newTime.getTime() - currentTime.getTime(); // Calculate the difference
    System.out.println("Time difference is: " + msDelay + " in ms");
}
Compruebe si ha pasado una cierta cantidad de tiempo:
public static void main(String[] args) throws Exception
{
    Date startTime = new Date();

    long endTime = startTime.getTime() + 5000;  //    +5 seconds
    Date endDate = new Date(endTime);

    Thread.sleep(3000);              // Wait 3 seconds

    Date currentTime = new Date();
    if(currentTime.after(endDate))// Check whether currentTime is after endDate
    {
        System.out.println("End time!");
    }
}
Determine cuánto tiempo ha pasado desde el comienzo del día:
public static void main(String[] args) throws Exception
{
    Date currentTime = new Date();
    int hours = currentTime.getHours();
    int mins = currentTime.getMinutes();
    int secs = currentTime.getSeconds();

    System.out.println("Time since midnight " + hours + ":" + mins + ":" + secs);
}
Determine cuántos días han pasado desde el comienzo del año:
public static void main(String[] args) throws Exception
{
    Date yearStartTime = new Date();
    yearStartTime.setHours(0);
    yearStartTime.setMinutes(0);
    yearStartTime.setSeconds(0);

    yearStartTime.setDate(1);      // First day of the month
    yearStartTime.setMonth(0);     // January (the months are indexed from 0 to 11)

    Date currentTime = new Date();
    long msTimeDifference = currentTime.getTime() - yearStartTime.getTime();
    long msDay = 24 * 60 * 60 * 1000;  // The number of milliseconds in 24 hours

    int dayCount = (int) (msTimeDifference/msDay); // The number of full days
    System.out.println("Days since the start of the year: " + dayCount);
}

"El getTime()método devuelve el número de milisegundos almacenados en un objeto Date".

"El after()método verifica si la fecha en la que llamamos al método es posterior a la fecha que se pasó al método".

"Los getHours(), getMinutes(), getSeconds()métodos devuelven la cantidad de horas, minutos y segundos, respectivamente, para el objeto en el que fueron llamados".

"Además, en el último ejemplo puede ver que puede cambiar la fecha/hora almacenada en un objeto Fecha . Obtenemos la hora y la fecha actuales y luego restablecemos las horas, los minutos y los segundos a 0. También configuramos enero como el mes y 1 como el día del mes. Así, el yearStartTimeobjeto almacena la fecha 1 de enero del año en curso y la hora 00:00:00".

"Después de eso, obtenemos nuevamente la fecha actual ( currentTime), calculamos la diferencia entre las dos fechas en milisegundos y la almacenamos en msTimeDifference".

"Luego dividimos msTimeDifferencepor la cantidad de milisegundos en 24 horas para obtener la cantidad de días completos desde el comienzo del año actual hasta hoy".

"¡Guau! ¡Esto es genial!"