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));
}
Comments
-
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 almost 10 yearsYou 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 needcompareTo(...)
, which would also allow you to do the comparison in one go), 2) that timestamps have fractional seconds. -
fipple almost 10 yearsThanks 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 over 5 yearsFYI, the terribly troublesome old date-time classes such as
java.util.Date
,java.util.Calendar
, andjava.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.