Comparing string date with today's date

14,102
    final String stringDate = "2014-07-17 23:59";

    SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    Date date = inputFormat.parse(stringDate);

    Calendar calendarDate = Calendar.getInstance();
    calendarDate.setTime(date);

    Calendar midnight = Calendar.getInstance();
    midnight.set(Calendar.HOUR_OF_DAY, 0);
    midnight.set(Calendar.MINUTE, 0);
    midnight.set(Calendar.SECOND, 0);
    midnight.set(Calendar.MILLISECOND, 0);

    if (calendarDate.compareTo(midnight) >= 0)
    {
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
        System.out.println(timeFormat.format(date));
    }
    else
    {
        SimpleDateFormat dateTimeForm = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        System.out.println(dateTimeForm.format(date));
    }
Share:
14,102
sok
Author by

sok

SOreadytohelp

Updated on June 05, 2022

Comments

  • sok
    sok almost 2 years

    So I have a string which is "2014-06-30 15:27" and if it is today's date it should only return "15:27" else "30/06/2014". I've already tried simpleDateFormat.parse but it didn't work very well.

    holder.data.setText(mensagem.getDate());
    
  • Clockwork-Muse
    Clockwork-Muse almost 10 years
    You forgot that 1) The incoming date might also be midnight (so, equal - unfortunately you can't use the .equals(...) method due to it considering things like timezone, you'd need compareTo(...) , which would also allow you to do the comparison in one go), 2) that timestamps have fractional seconds.
  • fipple
    fipple almost 10 years
    Thanks for the feedback. I've made a couple of edits to the code. Calendar.HOUR was a typo, should have been Calendar.HOUR_OF_DAY. Now using compareTo on Calendar for the date comparison. I also cleared the milliseconds on the midnight value.
  • Basil Bourque
    Basil Bourque over 5 years
    FYI, the terribly troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.