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
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
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);
I can see two ways:
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);
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.