计算当前日期是本年的第几周

    首先,需要了解一个国际标准:ISO8601,该标准是国际标准化组织用来定义日期和时间的表示方法,全称是《数据存储和交换形式·信息交换·日期和时间的表示方法》。其中有关第几周的计算,在WIKI上有如下描述:

日历星期和日表示法
可以用2位数表示本年内第几个日历星期,再加上一位数表示日历星期内第几天,但日历星期前要加上一个大写字母W,如2004年5月3日可写成2004-W17-3或2004W173。以1月4日所在的那个星期为当年的第一个星期,如:2005年1月1日是2004-W53-6,2005年1月3日是2005-W01-1。每个日历星期从星期一开始,星期日为第7天。

在上述描述中,需要重点关注两个方面:
1、每个日历星期从星期一开始,星期日为第七天。
2、以1月4日所在的那个星期为当年的第一个星期。

上述两项可以作为求今天是本年第几周的理论根据。

在jQuery UI的 datepicker中找到下面函数 ISO8601Week():

/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
 * @param  date  Date - the date to get the week for
 * @return  number - the number of the week within the year that contains this date
 */
iso8601Week: function(date) {
var time, checkDate = new Date(date.getTime());

// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));

time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
}

难点就在于跨年的计算上,但是结合上面ISO8601的规定,很容易理清楚jQueryUI中的思路。

如果1月4日为周一,则,1,2,3号是去年的最后一周。
如果1月4日为周二,则,1,2号是去年的最后一周。
如果1月4日为周三,则,1号为去年的最后一周。
如果1月4日为周四,则,周一即为开始。
如果1月4日为周五,则,侵占去年的最后一天。
如果1月4号为周六,则,侵占去年的最后两天。
如果1月4日为周日,则,侵占去年的最后三天。

由此可见,只需要根据当前日期所处的本周的周四,就可以推断出当前日期属于第几周了。可以根据所处的周四与本年度的一月一号比较,得到当前日期属于本年度的第几周,上面JQUERY的算法完全就是这个思路。有这个,我们就可以很容易的使用任何我们想用的语言来计算当前周是第几周了。

作者 陈字文(热衷于PM\ORACLE\JAVA等,欢迎同行交流)EMAIL:ziwen@163.com  QQ:409020100.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>datepicker demo</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body>
 
<div id="datepicker"></div>
 
<script>
$( "#datepicker" ).datepicker({ 
showWeek: true,
weekHeader: "W",
firstDay: 1,
changeMonth:true,
changeYear:true,
onSelect:function(date,inst){
alert(getWeek(date));
}
 });
 
function getWeek(date) {
var time,week,checkDate = new Date(date);
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0);
checkDate.setDate(1);
week=Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
return $.datepicker.formatDate('yy',checkDate)+'W'+(week<10?'0':'')+week;
}
</script>
 
</body>
</html>

上面的代码可以作为测试 .
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值