tags:

views:

50

answers:

2

HI

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

+2  A: 

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);
Dan Dyer
I think you should use Calendar.roll() instead of Calendar.add() if you want to handle month/year change right. Your example might be wrong between the 1st and 6th of january.
Kevin Gaudin
I think the opposite is true: roll() does not handle month/year changes when called on the date, while add() does.
Skip Head
Ok, my bad! ;-)
Kevin Gaudin
A: 

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.

Kevin Gaudin
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.
Dan Dyer
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.
Kevin Gaudin