Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to calculate a date some days ago?

I get the today's date like this:

final Calendar cal = Calendar.getInstance();
{
   mYear = cal.get(Calendar.YEAR);
   mMonth = cal.get(Calendar.MONTH);
   mDay = cal.get(Calendar.DAY_OF_MONTH);
}

I want to calculate what was the date x days ago... anyone got something?

like image 644
Alex Fragotsis Avatar asked Oct 07 '11 13:10

Alex Fragotsis


People also ask

How can I get the difference between two dates in days in Android?

startDateValue = new Date(startDate); endDateValue = new Date(endDate); long diff = endDateValue. getTime() - startDateValue. getTime(); long seconds = diff / 1000; long minutes = seconds / 60; long hours = minutes / 60; long days = (hours / 24) + 1; Log.

How can I compare current date and time with another date and time in Android?

By Calendar Object:getTime(); Date date2 = calendar2. getTime(); Then compare both date using compareTo, before(date) or after(date).

How do I get the time ago on my Android?

In Android you can use DateUtils. getRelativeTimeSpanString(long timeInMillis), referring to https://developer.android.com/reference/android/text/format/DateUtils.html you can use one of the variations of that method for accuracy.


3 Answers

A better way would be to use add method instead of set:

cal.add(DAY_OF_YEAR, -2);

I.e. to be sure it works also the first day in month etc.

like image 169
Jan Korpegård Avatar answered Oct 09 '22 04:10

Jan Korpegård


You can do the following :

    Calendar cal=Calendar.getInstance();
    int currentDay=cal.get(Calendar.DAY_OF_MONTH);
    //Set the date to 2 days ago
    cal.set(Calendar.DAY_OF_MONTH, currentDay-2);

then you can get the date :

    cal.getTime(); //The date 2 days ago
like image 25
Ovidiu Latcu Avatar answered Oct 09 '22 05:10

Ovidiu Latcu


I use the following fuction:

public static Date getStartOfDay() {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

public static long getDaysAgo(Date date){
    final long diff = getStartOfDay().getTime() - date.getTime();
    if(diff < 0){
    // if the input date millisecond > today's 12:00am millisecond it is today
    // (this won't work if you input tomorrow)
        return 0;
    }else{ 
        return TimeUnit.MILLISECONDS.toDays(diff)+1;
    }
}
like image 31
Krit Avatar answered Oct 09 '22 06:10

Krit