Compare Two dates and time

Asked

Viewed 7,481 times

3

Good morning guys, I’m trying to compare two dates but I’m not succeeding. I have 2 dates: dataAtual and dataPedido. What I want to do is that if the dateAtual is equal to datePedido and if the current time is greater than 11:00 AM a message appears. I tried to do it but it didn’t work:

public void getDateTime(Date dataPedido, Date dataSistema) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("HH:mm");
            Date horaAtual = new Date();
            String horaMaxima = "11:00";
            dateFormat.format(horaAtual);

            Date horaMax = null;
            horaMax = dateFormat.parse(horaMaxima);

            if (horaAtual.getTime() > horaMax.getTime() && dataPedido.compareTo(dataSistema) == 0) {
                System.err.println("HORA ATUAL MAIOR, nao pode fazer");
                horarioComparacao = false;

            } else {
                System.err.println("HORA ATUAL Menor, pode fazer");
                horarioComparacao = true;

            }
            System.err.println("HORA MAXIMA: " + horaMax);

        } catch (ParseException ex) {
            Logger.getLogger(frmPedidos.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

3 answers

5


If you use the class Calendar everything becomes simpler.

Write a method to convert an object Date in Calendar with the option of "zero" part of Team.

public static Calendar DateToCalendar(Date date, boolean setTimeToZero){ 
    Calendar calendario = Calendar.getInstance();
    calendario.setTime(date);
    if(setTimeToZero){
        calendario.set(Calendar.HOUR_OF_DAY, 0);
        calendario.set(Calendar.MINUTE, 0);
        calenario.set(Calendar.SECOND, 0);
        calendario.set(Calendar.MILLISECOND, 0);
    }
    return calendario;
}  

I suppose when you say "if the current date is equal to date..." is considering that they are equal regardless of the time.

Write a method to test conditions:

public boolean possoProcessarPedido(Date dataPedido) {

    Calendar dataAtualTimeZero = DateToCalendar(new Date(), true);
    Calendar dataPedidoTimeZero = DateToCalendar(dataPedido, true);

    if(dataAtualTimeZero.compareTo(dataPedidoTimeZero) != 0){
        // A data do pedido e a data atual são diferentes: pode processar
        return true;
    }

    Calendar dataAtual = DateToCalendar(new Date(), false);
    Calendar dataAtualAs11Horas  = DateToCalendar(new Date(), true);
    dataAtualAs11Horas.set(Calendar.HOUR_OF_DAY, 11);

    if(dataAtual.after(dataAtualAs11Horas){
        //As datas são iguias mas já passa das 11 horas: não pode processar
        return false;
    }
    // As datas são iguais e é antes das 11 horas: pode processar
    return true;
}  

Use the method as follows:

if(possoProcessarPedido(dataPedido){
    // código para processar pedido
}
  • 1

    I changed the code to simplify the condition that checks if it’s past 11:00

3

Just to complement the previous responses, from Java 8 you can use the API java.time.

There are some details to consider when working with the old API (java.util.Date) and the new one simultaneously, because some concepts are different. Then follows a brief explanation about Date, so that we can understand the conversion of this to the classes of the java.time.

About java.util.Date

java.util.Date, despite the name, it is not exactly a date per se, as it does not represent a single value of day, month and year. It actually represents a timestamp: a giant number (of the type long) containing the amount of milliseconds since Unix Epoch (1970-01-01T00:00Z, or "January 1, 1970, at midnight, at UTC").

Timestamp is a value, say, "universal". Right now, anywhere in the world, timestamp is the same. In Java, just call System.currentTimeMillis() and you will have the timestamp corresponding to the current instant. I checked now and the returned value was 1534249967760. And this value is the same all over the world: any computer, in any time zone in the world, would get this same number if it called System.currentTimeMillis() the same instant I.

Only that this value (1534249967760) can represent a different date/time in each time zone. In São Paulo, this timestamp is equivalent to August 14, 2018, 09:32:47,760 am. In London, it is the same day (14 August), but right now the time is there 13:32 (1 pm). And in Samoa are already 01:32 (1 am) of the day 15.

We can better see this by printing the Date (with System.out.println or with any log API). When printing it, it is converted to Timezone default JVM, so the result contains a specific date and time. But the value of the Date does not change. In the code below I use the class java.util.TimeZone to change the Timezone default:

// código rodado quando o timestamp atual é 1534249967760
Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("America/Sao_Paulo"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
System.out.println(date.getTime() + "=" + date);
TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Apia"));
System.out.println(date.getTime() + "=" + date);

I changed the Timezone default 3 times, for São Paulo, London and Apia (which is the Timezone of Samoa) and printed the Date and the value of getTime() (that returns the timestamp value). The result is:

1534249967760=Tue Aug 14 09:32:47 BRT 2018
1534249967760=Tue Aug 14 13:32:47 BST 2018
1534249967760=Wed Aug 15 01:32:47 WSST 2018

Note that the timestamp does not change, but the date and time does. This is because by printing the Date, it converts the timestamp to Timezone default, resulting in a different date and time in each case. But these date and time values are not part of the Date, only the timestamp.

Therefore, to convert a Date for a specific date (a specific day, month and year), you must choose a time zone (which the API calls Timezone). What happens to Calendar is that internally it uses the Timezone default JVM and already calculates values for day, month, year, hours, minutes, seconds etc.

But in the java.time this does not happen automatically and you must specify which Timezone should be used.

With this, we can proceed to the conversion of Date for the classes of java.time.

Convert Date for a specific date and time

First we convert the Date for java.time.Instant, which is the class that represents a timestamp. To this end the method has been added toInstant() (available from Java 8):

Date data = new Date();
// criar Instant (com o mesmo valor do timestamp de Date)
Instant instant = data.toInstant();

From the Instant, we can convert it to any Timezone, using the class java.time.ZoneId (representing a Timezone). The result will be a java.time.ZonedDateTime (a class representing a date and time in a specific Timezone). Example:

Date data = new Date();
ZonedDateTime zdt = data.toInstant()
    // converter o Instant para um timezone
    .atZone(ZoneId.of("America/Sao_Paulo"));

The name of Timezone (America/Sao_Paulo) follows the nomenclature of IANA, which is the database used by JVM to obtain information from Timezone (such as the beginning and end of daylight saving time, for example, so it can know exactly the date and time corresponding to the timestamp).

If you want to use Timezone default of the JVM (and thus simulate what Calendar makes), can use ZoneId.systemDefault(). At your discretion.

To get the current date, just use the method now():

ZonedDateTime agora = ZonedDateTime.now();

This creates a ZonedDateTime containing the current date and time on Timezone default JVM. If you want to use a specific Timezone, just pass the ZoneId:

ZonedDateTime agora = ZonedDateTime.now(ZoneId.of("America/Sao_Paulo"));

With this you get the correct values for the date and time in the Timezone you want, without depending on the JVM configuration (which you can change without knowing, because any part of the code can call TimeZone.setDefault, affecting all applications running on the same JVM).

To make the necessary comparisons, just use the method equals (to verify equality) and isAfter (to know if a given instant occurs after another).

The first comparison takes into account only the date (ignoring the time), so you should use the method toLocalDate(), that returns a java.time.LocalDate (a class that only has day, month and year), so the comparison is made by ignoring the schedule.

Then, for the second comparison, just use the method toLocalTime(), that returns a java.time.LocalTime (a class that only has hour, minute, second and fractions of a second). Next we compare with another java.time.Localtime the value of which is 11:00.

In fact, this is another characteristic of java.time: several specialized classes for each situation (one representing date only, one for hours only, one for date and time with Timezone, etc).

Anyway, the code would look like this (assuming you want to use Timezone default jvm):

public boolean possoProcessarPedido(Date dataPedido) {
    ZonedDateTime pedido = dataPedido.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime dataAtual = ZonedDateTime.now();

    // comparar somente a data (ignora o horário)
    if (! dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(LocalTime.of(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

If instead of Timezone default, you want to use a specific Timezone, just use the ZoneId corresponding, as explained above.

Java 6 and 7

For Java 6 and 7, you can use Threeten Backport, one backport of java.time. Basically, it has the same classes (Instant, LocalDate, ZoneId, etc) and Java 8 methods, with one difference: in Java 8 the classes are in the package java.time, and in the backport they stay in org.threeten.bp.

Another difference is that in Java 6 and 7 the class Date does not have the method toInstant() and the conversion shall be done by the class org.threeten.bp.DateTimeUtils:

Date date = new Date();
Instant instant = DateTimeUtils.toInstant(date);

The rest of the code would look the same.

Java <= 5

For Java <= 5, you can use Joda-Time. This API is the "predecessor" of java.time, and many concepts are similar (even some class names are the same), although it is not 100% the same.

The code looks very similar: instead of ZonedDateTime, we use the class org.joda.time.DateTime - by the way, all classes below (LocalDate, Localtime, etc), although they have the same names as the java.time, are in the package org.joda.time:

public boolean possoProcessarPedido(Date dataPedido) {
    DateTime pedido = new DateTime(dataPedido);
    DateTime dataAtual = new DateTime();

    // comparar somente a data
    if (!dataAtual.toLocalDate().equals(pedido.toLocalDate())) {
        // data do pedido e data atual são diferentes - pode processar
        return true;
    }
    // se não entrou no if acima é porque as datas são iguais

    // verificar se já passou das 11:00
    if (dataAtual.toLocalTime().isAfter(new LocalTime(11, 0))) {
        // passou das 11:00 - não pode processar
        return false;
    }

    // não passou das 11:00 - pode processar
    return true;
}

This code uses Timezone default JVM to convert the Date for DateTime. If you want to use a specific Timezone, use the class org.joda.time.DateTimeZone:

DateTimeZone timezone = DateTimeZone.forID("America/Sao_Paulo");
DateTime pedido = new DateTime(dataPedido, timezone);
DateTime dataAtual = new DateTime(timezone);

The method forID receives the name of Timezone, also following the nomenclature of IANA.

2

I think you better use the Legend class

Calendar dataAtual = new GregorianCalendar();   
    Calendar dataMAxima = new GregorianCalendar();   
    dataAtual.setTime(new Date());
    dataMAxima.set(Calendar.HOUR_OF_DAY, 11);
    dataMAxima.set(Calendar.MINUTE, 0);
    dataMAxima.set(Calendar.SECOND, 0);

in it vc have comparison methods, above I explain with passing a date and how to set an important date is set hour, minute and second

Browser other questions tagged

You are not signed in. Login or sign up in order to post.