繁体   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