0

How can serve a string as a date and reduce 2 day, after that return the result as an string ?

Just similar to the title example? Thanks

This is some related code but it seems deduct from current date and not output as a string like e.g. 20140308, thanks

Calendar calendar = Calendar.getInstance(); 
calendar.add(Calendar.DATE, -2);
user782104
  • 13,233
  • 55
  • 172
  • 312
  • Hope you have get him idea from the following link: http://stackoverflow.com/questions/21473696/android-display-date-from-one-week-to-another-like-thursday-to-thursday – Farhan Shah Mar 10 '14 at 12:17

2 Answers2

0

You first need to parse the date from the String into a Date something like this:

Date date = new SimpleDateFormat("yyyyMMdd").parse("YOUR DATE STRING");

Then set the time from that date, to the Calendar instance:

Calendar c = Calendar.getInstance();
c.setTime(date);

At this point, calendar's date is the one you had in your string, and you can deduct 2 days or whatever you want from that date and not today

c.add(Calendar.DATE, -2); 
Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
0

You can use SimpleDateFormat to parse your String as a Date based on the pattern of your choice - in your case it is yyyyMMdd.

Then you can perform operations on that date which you want to re-format as a String based on your pattern.

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); //Set SimpleDateFormat per your pattern
    String dateStr = "20140310"; // Your Date as String
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(dateStr)); // Set the date to Calendar instance
    cal.add(Calendar.DATE, -2); // Perform Operation

    System.out.println(sdf.format(cal.getTime())); //20140308
StoopidDonut
  • 8,547
  • 2
  • 33
  • 51