chefrisl
chefrisl

Reputation: 33

How can i get `String` date from calendar?

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?

Upvotes: 1

Views: 8858

Answers (4)

Marcel Pater
Marcel Pater

Reputation: 174

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
String strdate = sdf.format(calendardate.getTime());

Upvotes: 1

Prasad Khode
Prasad Khode

Reputation: 6739

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

Upvotes: 6

kondu
kondu

Reputation: 410

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.

Upvotes: 1

Marco Virgolin
Marco Virgolin

Reputation: 165

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());

Upvotes: 3

Related Questions