簡體   English   中英

如何獲得給定字符串日期的一周中的天數

[英]How to get the number of days in a week given a string date

我有一個字符串,它是String dateOfOrder = "01/06/2019";

我想獲取第1周的天數,因為6月的第一周只有1天。

我可以知道在X周減少天數怎么辦嗎?

如2019年6月

第1周:有1天;第2-5周:有7天;第6周:有1天

編輯

我正在考慮這種方法來獲得一個星期中的天數,因此我有幾個String arrayList。 例如,在上面給定的日期,如果第1周有星期六。 第1周數組列表將在其中添加星期六和.size()。 如果第2周有星期日至星期六,它將在第2周數組列表和.size()中添加所有日期,以獲取ArrayList中的天數。 最后,6月的最后一周(即第6周)將只有星期天,它將添加到第6周ArrayList中,並且僅具有Sunday的值和.size()來獲得1。

我想知道這是否是最好的方法,並且不確定是否可以在一周中得到正確的日子。

使用SimpleDateFormatter將字符串解析為日期。 您的解析模式可能是dd/MM/YYYY

DateFormat df = new SimpleDateFormat("dd/MM/YYYY"); 
Date date = df.parse(dateOfOrder);

確定日期后,使用Calendar獲取星期幾。

 Calendar c = Calendar.getInstance();
 c.setTime(yourDate);
 int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
 int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);

計算給定星期(和月份)中的天數。

int daysInMonth = c.getActualMaximum(Calendar.DAY_OF_MONTH);
int currentMonth = c.get(Calendar.MONTH);
int prevWeekMonth = c.add(Calendar.DAY_OF_MONTH, -7).get(Calendar.MONTH);

c.setTime(yourDate);
int nextWeekMonth = c.add(Calendar.DAY_OF_MONTH, 7).get(Calendar.MONTH);

c.setTime(yourDate);

if (prevWeekMonth != currentMonth) {
    // first or second week
    if (dayOfMonth > dayOfWeek) {
        // second week
        numOfDaysInWeek = 7;
    } else {
        // first week
        int firstDay = c.set(Calendar.DAY_OF_MONTH, 1).get(Calendar.DAY_OF_WEEK);
        numOfDaysInWeek = 7 - firstDay;
    }
} else if (nextWeekMonth != currentMonth) {
    // last or second last week
    if (dayOfMonth - dayOfWeek + 7 >= daysInMonth) {
         // last week
         numOfDaysInWeek = c.set(Calendar.DAY_OF_MONTH, daysInMonth).get(Calendar.DAY_OF_WEEK);
    } else {
         // second last week
         numOfDaysInWeek = 7;
    }
} else {
    // middle weeks
    numOfDaysInWeek = 7;
}

注意:條件有點粗糙 ,您可能需要添加1具體取決於dayOfWeek,dayOfMonth是0還是1索引。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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