I have following method:
public static String formatDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Calendar today = Calendar.getInstance();
Calendar yesterday = Calendar.getInstance();
yesterday.add(Calendar.DATE, -1);
DateFormat timeFormatter = new SimpleDateFormat("hh:mma");
DateFormat dateTimeFormatter = new SimpleDateFormat("MMM d, yyyy - hh:mma");
if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.HOUR_OF_DAY) == today.get(Calendar.HOUR_OF_DAY) && calendar.get(Calendar.MINUTE) == today.get(Calendar.MINUTE)) {
return "few seconds ago ";
} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) && calendar.get(Calendar.HOUR_OF_DAY) == today.get(Calendar.HOUR_OF_DAY)) {
return "few minutes ago ";
} else if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
return "today " + timeFormatter.format(date);
} else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) {
return "yesterday " + timeFormatter.format(date);
} else {
return dateTimeFormatter.format(date);
}
}
How do I write this in client side GWT?
There are four ways to do this that occur to me:
Calendar is not emulated in GWT on the client side.
in the Date class. They still work, and they’ve all been deprecated
in favour of methods in Calendar, so you’d just be rolling back the
clock a bit.
also just roll forward, as it were. Calendar emulation is coming to
GWT, at least that’s what I’ve read. You could do (1) for now, then
move that method to the client when Calendar arrives. Alternately,
you could do (2) for now, and swap it for your original
Calendar-based code when Calendar arrives.
Go for 4.
Use the methods in com.google.gwt.i18n.client.DateTimeFormat to do your date/time formatting.