How do I get the values of a date in the "dd/MM/yyyy hh:mm" format and compare it to the system date after setting it in this same format?

Asked

Viewed 178 times

4

I wanted to make a comparison between the date contained in the hora1 object and the system date, as I can do?

import java.text.SimpleDateFormat;
import java.util.Date;


public class MainTarefas {


    public static void main(String[] args) {
        Date horaMarcada = new Date(1,1,1,1,1);
        Date horaAtual = new Date();
        System.out.println(horaMarcada.compareTo(horaAtual));

    }

}

2 answers

3

Use the method compareTo

data1.compareTo(data2);

  • 1

    Although this way of comparing dates is correct in some contexts, it does not answer the question correctly, because the method compareTo will compare seconds and even milliseconds and not just the current time.

2


A generic solution to compare any parts of a date with only one parameter could be like this:

public class ComparadorData {

    public static boolean compareByPattern(Date d1, Date d2, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(d1).equals(sdf.format(d2));
    }

    public static void main(String[] args) {

        //forma mais adequada para criar uma data especificando ano, mês dia, hora e minuto
        //lembrando que o mês começa com zero (janeiro) e vai até 11 (dezembro)
        Calendar c = Calendar.getInstance();
        c.set(2014, 11, 30, 23, 59); // 30/12/2014 23:59
        Date horaMarcada = c.getTime();

        //hora atual
        Date horaAtual = new Date();

        //exibe resultado
        System.out.println("São Iguais? " +
                compareByPattern(horaMarcada, horaAtual, "yyyyMMddHHmm"));

    }

}
  • It worked, thanks!

Browser other questions tagged

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