Android get date before 7 days (one week)
Asked Answered
D

8

54

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

Determinate answered 19/9, 2010 at 21:11 Comment(1)
FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.Craunch
B
131

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);
Bluefarb answered 19/9, 2010 at 21:33 Comment(1)
I think the opposite is true: roll() does not handle month/year changes when called on the date, while add() does.Bashemeth
D
26

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
Dahlgren answered 1/1, 2015 at 5:11 Comment(2)
Wow.. great answer. Looking for this only.Hilary
second function should return s.format(cal.getTime())Ventilate
C
8

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();
Craunch answered 1/1, 2015 at 5:34 Comment(0)
W
4

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
Wrapping answered 5/11, 2019 at 13:41 Comment(1)
These terrible date-time classes were supplanted years ago by the industry-leading java.time classes defined in JSR 310.Craunch
M
1

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.

Maris answered 19/9, 2010 at 21:55 Comment(4)
The roll method doesn't affect any other fields, so you'll always be stuck in the same month, even if you try to go back 7 days from the first of the month.Bluefarb
You're right, I fixed the example. Anyway, my point was more on the usage of android.text.format.Time which is preferred if you are updating a date in a ListView item. Using GregorianCalendar could prevent your list from scrolling really fast.Maris
Thankyou, note fellow programmers the first example here should format (someDate.getTime()) rather than just someDateNecessarian
Time is deprecated.Boadicea
M
1

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

}
Microphyte answered 27/8, 2019 at 12:29 Comment(0)
D
1

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)
Dioptometer answered 17/9, 2020 at 14:7 Comment(0)
L
0
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);
Lucid answered 9/8, 2019 at 21:27 Comment(3)
FYI, the terribly troublesome date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.Craunch
FYI, the Joda-Time project is now in maintenance mode, advising migration to the java.time classes.Craunch
Using java.time is now possible on all APIs, Android gradle plugin in version 4.0.0 added support to Java 8 library desugaring in D8 and R8.Kirst

© 2022 - 2024 — McMap. All rights reserved.