Android get date before 7 days (one week)

I have created my own function that may helpful to get Next/Previous date from

Current Date:

/**
 * Pass your date format and no of days for minus from current 
 * If you want to get previous date then pass days with minus sign
 * else you can pass as it is for next date
 * @param dateFormat
 * @param days
 * @return Calculated Date
 */
public static String getCalculatedDate(String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    cal.add(Calendar.DAY_OF_YEAR, days);
    return s.format(new Date(cal.getTimeInMillis()));
}

Example:

getCalculatedDate("dd-MM-yyyy", -10); // It will gives you date before 10 days from current date

getCalculatedDate("dd-MM-yyyy", 10);  // It will gives you date after 10 days from current date

and if you want to get Calculated Date with passing Your own date:

public static String getCalculatedDate(String date, String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    cal.add(Calendar.DAY_OF_YEAR, days);
    try {
        return s.format(new Date(s.parse(date).getTime()));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        Log.e("TAG", "Error in Parsing Date : " + e.getMessage());
    }
    return null;
}

Example with Passing own date:

getCalculatedDate("01-01-2015", "dd-MM-yyyy", -10); // It will gives you date before 10 days from given date

getCalculatedDate("01-01-2015", "dd-MM-yyyy", 10);  // It will gives you date after 10 days from given date

tl;dr

LocalDate
    .now( ZoneId.of( "Pacific/Auckland" ) )           // Get the date-only value for the current moment in a specified time zone.
    .minusWeeks( 1 )                                  // Go back in time one week.
    .atStartOfDay( ZoneId.of( "Pacific/Auckland" ) )  // Determine the first moment of the day for that date in the specified time zone.
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a string in standard ISO 8601 format.
    .replace( "T" , " " )                             // Replace the standard "T" separating date portion from time-of-day portion with a SPACE character.

java.time

The modern approach uses the java.time classes.

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.forID( "America/Montreal" ) ;
LocalDate now = LocalDate.now ( z ) ;

Do some math using the minus… and plus… methods.

LocalDate weekAgo = now.minusWeeks( 1 );

Let java.time determine the first moment of the day for your desired time zone. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time means the day may start at another time-of-day such as 01:00:00.

ZonedDateTime weekAgoStart = weekAgo.atStartOfDay( z ) ;

Generate a string representing this ZonedDateTime object using a DateTimeFormatter object. Search Stack Overflow for many more discussions on this class.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = weekAgoStart.format( f ) ;

That standard format is close to what you want, but has a T in the middle where you want a SPACE. So substitute SPACE for T.

output = output.replace( "T" , " " ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use ThreeTenABP….

Joda-Time

Update: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Using the Joda-Time library makes date-time work much easier.

Note the use of a time zone. If omitted, you are working in UTC or the JVM's current default time zone.

DateTime now = DateTime.now ( DateTimeZone.forID( "America/Montreal" ) ) ;
DateTime weekAgo = now.minusWeeks( 1 );
DateTime weekAgoStart = weekAgo.withTimeAtStartOfDay();

Parse the date:

Date myDate = dateFormat.parse(dateString);

And then either figure out how many milliseconds you need to subtract:

Date newDate = new Date(myDate.getTime() - 604800000L); // 7 * 24 * 60 * 60 * 1000

Or use the API provided by the java.util.Calendar class:

Calendar calendar = Calendar.getInstance();
calendar.setTime(myDate);
calendar.add(Calendar.DAY_OF_YEAR, -7);
Date newDate = calendar.getTime();

Then, if you need to, convert it back to a String:

String date = dateFormat.format(newDate);

Tags:

Java

Date

Android