小编典典

像在PHP中一样获得一年中的JavaScript

javascript

我如何获得年度的当前星期数,例如PHP的星期数date('W')

它应该是ISO-8601的 星期数,从星期一开始的星期数。


阅读 403

收藏
2020-04-25

共1个答案

小编典典

在观察夏令时和1月1日是星期五的年份中,日期存在问题。通过使用所有UTC方法进行修复。以下代码将相同的结果返回给Moment.js。

/* For a given date, get the ISO week number

 *

 * Based on information at:

 *

 *    http://www.merlyn.demon.co.uk/weekcalc.htm#WNR

 *

 * Algorithm is to find nearest thursday, it's year

 * is the year of the week number. Then get weeks

 * between that date and the first day of that year.

 *

 * Note that dates in one year can be weeks of previous

 * or next year, overlap is up to 3 days.

 *

 * e.g. 2014/12/29 is Monday in week  1 of 2015

 *      2012/1/1   is Sunday in week 52 of 2011

 */

function getWeekNumber(d) {

    // Copy date so don't modify original

    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));

    // Set to nearest Thursday: current date + 4 - current day number

    // Make Sunday's day number 7

    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));

    // Get first day of year

    var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));

    // Calculate full weeks to nearest Thursday

    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);

    // Return array of year and week number

    return [d.getUTCFullYear(), weekNo];

}



var result = getWeekNumber(new Date());

document.write('It\'s currently week ' + result[1] + ' of ' + result[0]);

创建“ UTC”日期时,小时为零。

最小化的原型版本(仅返回星期数):

Date.prototype.getWeekNumber = function(){

  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));

  var dayNum = d.getUTCDay() || 7;

  d.setUTCDate(d.getUTCDate() + 4 - dayNum);

  var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));

  return Math.ceil((((d - yearStart) / 86400000) + 1)/7)

};



document.write('The current ISO week number is ' + new Date().getWeekNumber());

测试部分

在本部分中,您可以输入YYYY-MM-DD格式的任何日期,并检查该代码是否具有与Moment.js
ISO周号相同的周号(在2000年至2050年的50年中进行了测试)。

Date.prototype.getWeekNumber = function(){

  var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate()));

  var dayNum = d.getUTCDay() || 7;

  d.setUTCDate(d.getUTCDate() + 4 - dayNum);

  var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));

  return Math.ceil((((d - yearStart) / 86400000) + 1)/7)

};



function checkWeek() {

  var s = document.getElementById('dString').value;

  var m = moment(s, 'YYYY-MM-DD');

  document.getElementById('momentWeek').value = m.format('W');

  document.getElementById('answerWeek').value = m.toDate().getWeekNumber();

}


<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>



Enter date  YYYY-MM-DD: <input id="dString" value="2021-02-22">

<button onclick="checkWeek(this)">Check week number</button><br>

Moment: <input id="momentWeek" readonly><br>

Answer: <input id="answerWeek" readonly>
2020-04-25