Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get date before 7 days (one week)

Tags:

java

date

android

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

like image 517
Jovan Avatar asked Sep 19 '10 21:09

Jovan


2 Answers

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); 
like image 98
Dan Dyer Avatar answered Oct 08 '22 19:10

Dan Dyer


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
like image 26
Pratik Butani Avatar answered Oct 08 '22 18:10

Pratik Butani