How to find time is today or yesterday in android How to find time is today or yesterday in android android android

How to find time is today or yesterday in android


To check if date is today, use Android utils library

DateUtils.isToday(long timeInMilliseconds)

This utils class also offers human readable strings for relative times. For example,

DateUtils.getRelativeTimeSpanString(long timeInMilliseconds) -> "42 minutes ago"

The are several parameters you can play with to define how precise the time span should be

See DateUtils


As mentioned, DateUtils.isToday(d.getTime()) will work for determining if Date d is today. But some responses here don't actually answer how to determine if a date was yesterday. You can also do that easily with DateUtils:

public static boolean isYesterday(Date d) {    return DateUtils.isToday(d.getTime() + DateUtils.DAY_IN_MILLIS);}

Following that, you could also determine if a date was tomorrow:

public static boolean isTomorrow(Date d) {    return DateUtils.isToday(d.getTime() - DateUtils.DAY_IN_MILLIS);}


You can do that easily using android.text.format.DateFormat class. Try something like this.

public String getFormattedDate(Context context, long smsTimeInMilis) {    Calendar smsTime = Calendar.getInstance();    smsTime.setTimeInMillis(smsTimeInMilis);    Calendar now = Calendar.getInstance();    final String timeFormatString = "h:mm aa";    final String dateTimeFormatString = "EEEE, MMMM d, h:mm aa";    final long HOURS = 60 * 60 * 60;    if (now.get(Calendar.DATE) == smsTime.get(Calendar.DATE) ) {        return "Today " + DateFormat.format(timeFormatString, smsTime);    } else if (now.get(Calendar.DATE) - smsTime.get(Calendar.DATE) == 1  ){        return "Yesterday " + DateFormat.format(timeFormatString, smsTime);    } else if (now.get(Calendar.YEAR) == smsTime.get(Calendar.YEAR)) {        return DateFormat.format(dateTimeFormatString, smsTime).toString();    } else {        return DateFormat.format("MMMM dd yyyy, h:mm aa", smsTime).toString();    }}

Check http://developer.android.com/reference/java/text/DateFormat.html for further understanding.