Manikandan Manikandan - 1 year ago 83
Android Question

How to find time is today or yesterday in android

Iam developing an application for sending sms. Iam storing the current time and showing in the sent history page by retrieving the time from the database. In the sent history page i want to display the time of the message was sent. Here i want to check that the message has been sent today or yesterday or the yesterday before like that. If the message was sent yesterday means then i need to display "Yesterday 20:00" like that and even the message was sent yesterday before means "Monday 20:00". I dont know how it has to be done. Please help me if anybody knows.

Answer Source

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();

    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 for further understanding.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download