Java判断日期是不是是本日,本周,本月
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java判断日期是不是是本日,本周,本月相关的知识,希望对你有一定的参考价值。
public static void main(String[] args)SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Calendar firstDayOfWeek = Calendar.getInstance(Locale.getDefault());
firstDayOfWeek.setFirstDayOfWeek(Calendar.MONDAY);
int day = firstDayOfWeek.get(Calendar.DAY_OF_WEEK);
firstDayOfWeek.add(Calendar.DATE, -day+1+1);// 后面的+1是因为从周日开始
// 本周一的日期
System.out.println(format.format(firstDayOfWeek.getTime()));
Calendar lastDayOfWeek = Calendar.getInstance(Locale.getDefault());
lastDayOfWeek.setFirstDayOfWeek(Calendar.MONDAY);
day = lastDayOfWeek.get(Calendar.DAY_OF_WEEK);
lastDayOfWeek.add(Calendar.DATE, 7-day+1);
// 本周星期天的日期
System.out.println(format.format(lastDayOfWeek.getTime()));
这一段代码可以获取本周一的日期、本周日的日期,比如本周一为20180702、本周日为20180708。只要判断给定的日期数字是否在[20180702, 20180708]范围内即可
以上的是判断日期是否是本周的方法,至于本日和本月就很好判断了,直接将日期格式化为20180702类似的数字,然后与今天进行比较即可判断是否本日,与本月的字符串201807进行比较,看字符串的前面6个字符是否equals即可
获取本周上周本月上月 的开始日期和结束日期
方法返回的是一个对象: {startDate: 年-月-日, endDate: 年-月-日}
使用方法: 获取上月 :getAppointedDate(2, 1) 获取上周 getAppointedDate(1, 1)
获取本月 :getAppointedDate(2, 0) 获取本周 getAppointedDate(1, 0)
获取下月 :getAppointedDate(2, -1) 获取下周 getAppointedDate(1, -1)
这规律大家应该都知道啦吧! html 中: num=0 为本月/本周, 上月/上周 按钮: 《 每点击一次就 num +=1,时间即为getAppointedDate(2, num) ; 下月/下周 按钮:》 num -=1
//获取本周、上周、本月、上月 的开始日期和结束日期 年-月-日
//optType: 1 获取周、 2 获取月
//optPageNum: 0 本周/本月; 上周/月 1 , 1+n
getAppointedDate(optType,optPageNum){
let now = new Date(), //当前日期
nowDayOfWeek = now.getDay(), //今天本周的第几天
nowDay = now.getDate(), //当前日
nowMonth = now.getMonth(), //当前月
nowYear = now.getFullYear(), //当前年
lastMonth = nowMonth -1 ;
let startDate = ‘‘, endDate= ‘‘;
if(optType==1){
startDate = this.formatDateFn (new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1 - (7*optPageNum)))
endDate = this.formatDateFn (new Date(nowYear, nowMonth, nowDay + 7 - nowDayOfWeek -(7*optPageNum) ))
} else if(optType==2) {
startDate = this.formatDateFn (new Date(nowYear, lastMonth+1-(1*optPageNum), 1))
endDate = this.formatDateFn (new Date(nowYear, lastMonth+1-(1*optPageNum) , this.getMonthDays(nowYear,lastMonth+1-(1*optPageNum)) ))
}
return {startDate: startDate, endDate: endDate}
},
getMonthDays(nowYear,myMonth) {
let monthStartDate = new Date(nowYear, myMonth, 1);
let monthEndDate = new Date(nowYear, myMonth + 1, 1);
let days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
return days;
},
formatDateFn(date) {
let myyear = date.getFullYear();
let mymonth = date.getMonth() + 1;
let myweekday = date.getDate();
if (mymonth < 10) {
mymonth = "0" + mymonth;
}
if (myweekday < 10) {
myweekday = "0" + myweekday;
}
return (myyear + "-" + mymonth + "-" + myweekday);
},
以上是关于Java判断日期是不是是本日,本周,本月的主要内容,如果未能解决你的问题,请参考以下文章
在sql server 2008中如何查询本日、本周和本月数据