Android get date before 7 days (one week)

JavaAndroidDate

Java Problem Overview


How to get date before one week from now in android in this format:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

ex: now 2010-09-19 HH:mm:ss, before one week 2010-09-12 HH:mm:ss

Thanks

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

Solution 3 - Java

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?

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

Solution 4 - Java

#Try this

One single method for getting the date from current or bypassing any date

@Pratik Butani's second method for getting the date from our own date is not working at my end.

Kotlin

fun getCalculatedDate(date: String, dateFormat: String, days: Int): String {
    val cal = Calendar.getInstance()
    val s = SimpleDateFormat(dateFormat)
    if (date.isNotEmpty()) {
        cal.time = s.parse(date)
    }
    cal.add(Calendar.DAY_OF_YEAR, days)
    return s.format(Date(cal.timeInMillis))
}

Java

 public static String getCalculatedDate(String date,String dateFormat, int days) {
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat s = new SimpleDateFormat(dateFormat);
    if (!date.isEmpty()) {
        try {
            cal.setTime(s.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    cal.add(Calendar.DAY_OF_YEAR, days);
    return s.format(new Date(cal.getTimeInMillis()));
}

#Usage

  1. getCalculatedDate("", "yyyy-MM-dd", -2) // If you want date from today
  2. getCalculatedDate("2019-11-05", "yyyy-MM-dd", -2) // If you want date from your own

Solution 5 - Java

I can see two ways:

  1. Use a GregorianCalendar:

    Calendar someDate = GregorianCalendar.getInstance();
    someDate.add(Calendar.DAY_OF_YEAR, -7);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String formattedDate = dateFormat.format(someDate);
    
  2. Use a android.text.format.Time:

    long yourDateMillis = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000);
    Time yourDate = new Time();
    yourDate.set(yourDateMillis);
    String formattedDate = yourDate.format("%Y-%m-%d %H:%M:%S");
    

Solution 1 is the "official" java way, but using a GregorianCalendar can have serious performance issues so Android engineers have added the android.text.format.Time object to fix this.

Solution 6 - Java

public static Date getDateWithOffset(int offset, Date date){
    Calendar calendar = calendar = Calendar.getInstance();;
    calendar.setTime(date);
    calendar.add(Calendar.DAY_OF_MONTH, offset);
    return calendar.getTime();
}

Date weekAgoDate = getDateWithOffset(-7, new Date());

OR using Joda:

add Joda library

    implementation 'joda-time:joda-time:2.10'

'

DateTime now = new DateTime();
DateTime weekAgo = now.minusWeeks(1);
Date weekAgoDate = weekAgo.toDate()// if you want to convert it to Date

-----------------------------UPDATE-------------------------------

Use Java 8 APIs or ThreeTenABP for Android (minSdk<24).

ThreeTenABP:

implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'

'

LocalDate now= LocalDate.now();
now.minusWeeks(1);

Solution 7 - Java

You can use this code for get exact string which you want.

object DateUtil{
    fun timeAgo(context: Context, time_ago: Long): String {
        val curTime = Calendar.getInstance().timeInMillis / 1000
        val timeElapsed = curTime - (time_ago / 1000)
        val minutes = (timeElapsed / 60).toFloat().roundToInt()
        val hours = (timeElapsed / 3600).toFloat().roundToInt()
        val days = (timeElapsed / 86400).toFloat().roundToInt()
        val weeks = (timeElapsed / 604800).toFloat().roundToInt()
        val months = (timeElapsed / 2600640).toFloat().roundToInt()
        val years = (timeElapsed / 31207680).toFloat().roundToInt()

        // Seconds
        return when {
            timeElapsed <= 60 -> context.getString(R.string.just_now)
            minutes <= 60 -> when (minutes) {
                1 -> context.getString(R.string.x_minute_ago, minutes)
                else -> context.getString(R.string.x_minute_ago, minutes)
            }
            hours <= 24 -> when (hours) {
                1 -> context.getString(R.string.x_hour_ago, hours)
                else -> context.getString(R.string.x_hours_ago, hours)
            }
            days <= 7 -> when (days) {
                1 -> context.getString(R.string.yesterday)
                else -> context.getString(R.string.x_days_ago, days)
            }
            weeks <= 4.3 -> when (weeks) {
                1 -> context.getString(R.string.x_week_ago, weeks)
                else -> context.getString(R.string.x_weeks_ago, weeks)
            }
            months <= 12 -> when (months) {
                1 -> context.getString(R.string.x_month_ago, months)
                else -> context.getString(R.string.x_months_ago, months)
            }
            else -> when (years) {
                1 -> context.getString(R.string.x_year_ago, years)
                else -> context.getString(R.string.x_years_ago, years)
            }
        }
    }

}

Solution 8 - Java

Kotlin:

import java.util.*

val Int.week: Period
    get() = Period(period = Calendar.WEEK_OF_MONTH, value = this)

internal val calendar: Calendar by lazy {
    Calendar.getInstance()
}

operator fun Date.minus(duration: Period): Date {
    calendar.time = this
    calendar.add(duration.period, -duration.value)
    return calendar.time
}

data class Period(val period: Int, val value: Int)

Usage:

val newDate = oldDate - 1.week
// Or val newDate = oldDate.minus(1.week)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJovanView Question on Stackoverflow
Solution 1 - JavaDan DyerView Answer on Stackoverflow
Solution 2 - JavaPratik ButaniView Answer on Stackoverflow
Solution 3 - JavaBasil BourqueView Answer on Stackoverflow
Solution 4 - JavaSunilView Answer on Stackoverflow
Solution 5 - JavaKevin GaudinView Answer on Stackoverflow
Solution 6 - JavaIslam AssiView Answer on Stackoverflow
Solution 7 - JavaPrashant JajalView Answer on Stackoverflow
Solution 8 - JavaCoolMindView Answer on Stackoverflow