1

How can i get String date from calendar?

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MOUNTH, -5); //set now and 5 days to back

I want get String like this(date on interval -5 days to TODAY):

11.03.2015
10.03.2015
.
.
.
07.03.2015

It's possible? How?

chefrisl
  • 33
  • 1
  • 4

4 Answers4

6

you can use for loop and reduce one day from calendar instance and print it

Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");

for (int index = 1; index <= 5; index++) {
    calendar.add(Calendar.DATE, -1);
    System.out.println(dateFormat.format(calendar.getTime()));
}

output:

10.03.2015
09.03.2015
08.03.2015
07.03.2015
06.03.2015
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
3

You should use the SimpleDateFormat class, as follows.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MOUNTH -5);
SimpleDateFormat myDateFormat = new SimpleDateFormat("MM.dd.yyyy"); //or ("dd.MM.yyyy"), If you want days before months.
String formattedDate = myDateFormat.format(cal.getTime());
1
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());
Prasad Khode
  • 6,602
  • 11
  • 44
  • 59
Marcel Pater
  • 164
  • 10
  • I want get String date on interval -5 days to TODAY – chefrisl Mar 11 '15 at 13:08
  • Please add explanations to your answer. – ADreNaLiNe-DJ Jul 11 '17 at 09:18
  • Thank you for this code snippet, which may provide some immediate help. A proper explanation would [greatly improve](https://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. – basvk Jul 11 '17 at 09:46
1
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
Long beforeTime = date - (5*24*60*60*1000);
Date beforeDate = new Date(beforeTime);
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
String s = format.format(beforeDate);

s returns the date in your required format.

kondu
  • 410
  • 3
  • 11
  • I want get String date on interval -5 days to TODAY – chefrisl Mar 11 '15 at 13:08
  • You can use the below logic in place of date in the above code snippet. (I modified it in the snippet above) Long beforeTime = (date.getTime())-(5*24*60*60*1000); Date beforeDate = new Date(beforeTime); – kondu Mar 11 '15 at 13:11