I am trying to get last week start date and end date from current date. And in my application week starts on Monday. For that I am using
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, 2);
Try this
protected void getpreviousweek(int num) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
c.add(Calendar.DATE, num * 7);
// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
ArrayList<String> listDate = new ArrayList<String>();
for (int i = 0; i < 7; i++)
{
listDate.add(df.format(c.getTime()));
c.add(Calendar.DAY_OF_MONTH, 1);
}
}
Pass num = -1 and check. You will get all the days of previous week. If you want first and last date then
String startDate =listDate.get(0);
String endDate = listDate.get(6); // do this after for loop.
You can use Calendar for do this:
Date date = new Date();
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH); // Jan = 0, dec = 11
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
int weekOfMonth= calendar.get(Calendar.WEEK_OF_MONTH);
System.out.println(sdf.format(calendar.getTime()));
System.out.println("year \t\t: " + year);
System.out.println("month \t\t: " + month);
System.out.println("dayOfMonth \t: " + dayOfMonth);
System.out.println("dayOfWeek \t: " + dayOfWeek);
System.out.println("weekOfYear \t: " + weekOfYear);
System.out.println("weekOfMonth \t: " + weekOfMonth);
if you know the the current day of the week you can calculate the last and the first day.
For example subtract 5 days:
calendar.add(Calendar.DAY_OF_MONTH, -5);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.