栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何找到给定月份的周六和周日?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何找到给定月份的周六和周日?

最简单 的方法是只迭代所有在一个月的日子里,检查一周的某一天为他们每个人。例如:

// This takes a 1-based month, e.g. January=1. If you want to use a 0-based// month, remove the "- 1" later on.public int countWeekendDays(int year, int month) {    Calendar calendar = Calendar.getInstance();    // Note that month is 0-based in calendar, bizarrely.    calendar.set(year, month - 1, 1);    int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);    int count = 0;    for (int day = 1; day <= daysInMonth; day++) {        calendar.set(year, month - 1, day);        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);        if (dayOfWeek == Calendar.SUNDAY || dayOfweek == Calendar.SATURDAY) { count++; // Or do whatever you need to with the result.        }    }    return count;}

绝对可以确定 ,这样做的方式要高效得多-但这就是我的出发点,当发现速度太慢时进行优化。

请注意,如果您能够使用Joda Time,那将使您的生活更加轻松…



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/498385.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号