[英]android- how to get the start date and end date of last week of the current month
我正在尝试从当前日期获取上周的开始日期和结束日期。 在我的申请周中,星期一开始。 为此,我正在使用
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, 2);
尝试这个
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);
}
}
传递num = -1并检查。 您将获得上周的所有日子。 如果您想要第一个和最后一个日期,那么
String startDate =listDate.get(0);
String endDate = listDate.get(6); // do this after for loop.
您可以使用日历来做到这一点:
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);
如果您知道星期几,则可以计算最后一天和第一天。
例如减去5天:
calendar.add(Calendar.DAY_OF_MONTH, -5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.