Search code examples
androidtime

How to find time is today or yesterday in android


I am developing an application for sending SMS. I am 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 the day before yesterday 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 don't know how it has to be done. Please help me if anybody knows.


Solution

  • 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.