PHP版:javascript
<?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版:php
<!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>