簡體   English   中英

android-如何獲取當月最后一周的開始日期和結束日期

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM