Apresentando o tipo Data - 1

"Oi, amigo. Quero falar sobre um tipo interessante chamado Date. Esse tipo armazena a data e a hora, e também pode medir intervalos de tempo."

"Parece interessante. Por favor, continue."

"Todo objeto Date armazena uma hora de uma forma bastante interessante: o número de milissegundos desde 1º de janeiro de 1970, GMT."

"Uau!"

"Sim. Este número é tão grande que não há espaço suficiente para ele em um int , então ele deve ser armazenado em um long . Mas é muito útil para calcular a diferença entre duas datas quaisquer. Basta fazer a subtração para encontrar a diferença com precisão ao milissegundo. Também resolve o problema da linha da data e do horário de verão."

"O mais interessante é que cada objeto é inicializado com a hora atual em sua criação. Para saber a hora atual, basta criar um objeto Date."

"Como você trabalha com isso?"

"Aqui estão alguns exemplos:"

Obter a data atual:
public static void main(String[] args) throws Exception
{
     Date today = new Date();
     System.out.println("Current date: " + today);
}
Calcule a diferença entre as duas datas
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");
}
Verifique se um determinado período de tempo passou:
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 quanto tempo se passou desde o início do dia:
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 quantos dias se passaram desde o início do ano:
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);
}
2
Tarefa
Java Syntax,  nível 8lição 4
Bloqueado
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"O getTime()método retorna o número de milissegundos armazenados em um objeto Date."

"O after()método verifica se a data em que chamamos o método vem depois da data passada para o método."

"Os getHours(), getMinutes(), getSeconds()métodos retornam o número de horas, minutos e segundos, respectivamente, para o objeto no qual foram chamados."

"Além disso, no último exemplo, você pode ver que pode alterar a data/hora armazenada em um objeto Date . Obtemos a hora e a data atuais e, em seguida, redefinimos as horas, minutos e segundos para 0. Também definimos janeiro como o mês e 1 como o dia do mês. Assim, o yearStartTimeobjeto armazena a data 1º de janeiro do ano atual e a hora 00:00:00."

"Depois disso, obtemos novamente a data atual ( currentTime), calculamos a diferença entre as duas datas em milissegundos e armazenamos em msTimeDifference."

"Em seguida, dividimos msTimeDifferencepelo número de milissegundos em 24 horas para obter o número de dias completos desde o início do ano atual até hoje."

"Uau, isso é tão legal!"