获取每月的周信息
PHP版:
<?php $current_year=2017; $current_month=10; $firstday = strtotime($current_year.'-'.$current_month.'-01'); //计算本月头一天的星期一 $monday=$firstday-86400*(date('N',$firstday)-1);//计算第一个周一的日期 //由于每个月只有四周 让 $i 从 1 到 5 增加即可 for ($i=1; $i <= 5; $i++) { $start=date("Y-m-d",$monday+($i-1)*86400*7);//起始周一 $end=date("Y-m-d",$monday+$i*86399*7);//结束周日 if(date('m',$monday+$i*86399*7)!=$current_month) { continue; } echo '第'.$i.'周 '.$start.' ~ '.$end."<br/>";//开始结束放入数组 } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> </body> </html>
JS版:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <script type="text/javascript"> /** * 获取当前时间 */ function p(s) { return s < 10 ? '0' + s : s; } //根据时间获取当前月的周数,每周的周日为一周的开始 function getWeekByMonth(date) { var y = date.getFullYear(); var m = date.getMonth(); //月份 var d = date.getDate(); var now2 = y + '-' + p(m) + "-" + p(d); //获取本月1号对应的周数 var monOneWeek = new Date(y, m - 1, 1); var week = monOneWeek.getDay(); //获取本月的天数 var monOneDay = new Date(y, m, 1); var date_count = (new Date(monOneDay.getTime() - 1000 * 60 * 60 * 24)).getDate(); var days = date_count; var mod = 7 - week; var count = 1; var start = 1; //起始日期 1 号开始 var s = "", ss = ""; var end = start + mod - 1; //截止日期 while (days >= 0) { //var end = start + 6; end = end > date_count ? date_count : end; s += "第" + count + "周:" + y + "年" + p(m) + "月" + "(" + p(start) + "-" + p(end) + ");" + "<br>"; start = end + 1; end += 7; days -= 7; ss += days + ","; count++; } return s; } function getData() { //2017年10月1日 var date5 = new Date(2017, 10, 01); document.write(getWeekByMonth(date5)); } getData(); </script> </head> <body> </body> </html>