Android: How to calculate a date some days ago?
Asked Answered
A

4

5

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?

Anoxemia answered 7/10, 2011 at 13:58 Comment(2)
not really the same question..Corgi
See Answer https://mcmap.net/q/121206/-android-get-date-before-7-days-one-weekRissole
I
12

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.

Ingratitude answered 7/10, 2011 at 20:42 Comment(0)
C
3

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
Corgi answered 7/10, 2011 at 14:2 Comment(0)
L
3

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;
    }
}
Langland answered 15/5, 2015 at 21:5 Comment(0)
S
1

Same kind of code, but using the Joda-Time 2.3 library and Java 7.

DateTime dateTime = new DateTime( 2014, 2, 3, 7, 8, 9 );
DateTime twoDaysPrior = dateTime.minusDays( 2 );
dateTime: 2014-02-03T07:08:09.000-08:00
twoDaysPrior: 2014-02-01T07:08:09.000-08:00
Stafani answered 6/1, 2014 at 18:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.