//explain
public class DateLoop {
static String finalDate;
static String particularDate;
public static void main(String[] args) {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy ");
Calendar cal = Calendar.getInstance();
particularDate = "2-1-2018";
// get starting date
cal.add(Calendar.DAY_OF_YEAR, -7);
// loop adding one day in each iteration
for(int i = 0; i< 7; i++){
cal.add(Calendar.DAY_OF_YEAR, 1);
finalDate =sdf.format(cal.getTime());
System.out.println(finalDate);
//ie, its giving previous 7 dates from present date, but I want
//particular date... thanks in advance
}
}
}
ie, its giving previous 7 dates from present date, but I want previous 7 dates from particular date.
tl;dr
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Use
LocalDate
for a date-only without time-of-day.Using the
Month
enum.Using month numbers, 1-12 for January-December.
Collect a sequence of dates.
For earlier Android, use the ThreeTen-Backport and ThreeTenABP projects.
if you want to have some date from some data do something like below.
As Uta Alexandru and Basil Bourque have said already, don’t use the long outmoted classes
SimpleDateFormat
andCalendar
.java.time
, the modern Java date and time API also known as JSR-310, is so much nicer to work with:This prints:
Not only is the code slightly simpler and shorter, more importantly, it is clearer and more natural to read.
Question: Can I use
java.time
on Android?You certainly can. It just requires at least Java 6.
Links
java.time
.