android-如何获取当月上周的开始日期和结束日期

时间:2014-06-17 09:13:12

标签: android

我想从上一个日期开始上周开始日期和结束日期。 在我的申请周从星期一开始。为此,我正在使用

Calendar c = Calendar.getInstance();

c.set(Calendar.DAY_OF_WEEK, 2);

2 个答案:

答案 0 :(得分:5)

试试这个

    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.

答案 1 :(得分:0)

您可以使用日历执行此操作:

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