像PHP一样在JavaScript中获取一年中的一周

Pee*_*Haa 127 javascript date

我如何得到当年的当前周数,如PHP date('W')

它应该是ISO-8601周的一周,从周一开始的几周.

Rob*_*obG 258

你应该能够得到你想要的东西:http://www.merlyn.demon.co.uk/js-date6.htm#YWD.

同一网站上更好的链接是:使用周数.

编辑

以下是一些代码,这些代码基于所提供的链接以及Dommer发布的预告片.在http://www.merlyn.demon.co.uk/js-date6.htm#YWD上对结果进行了轻微测试.请彻底测试,不提供任何保证.

编辑2017

在观察到夏令时期间以及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]);
Run Code Online (Sandbox Code Playgroud)

创建"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());
Run Code Online (Sandbox Code Playgroud)

测试部分

在本节中,您可以输入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();      
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 今天,2016年1月4日,我注意到添加"d.setMilliseconds(0)"也是必要的 - 它会在同一日期显示不同的周数,具体取决于我是使用新的Date()还是新的Date("1 /二千〇一十六分之四" ).只是为那些可能会遇到同样情况的人提供帮助. (16认同)
  • 此代码将2011年1月2日计算为2010年的第53周,应该是第52周.这在原始代码中正常工作,但在您的改编中没有. (8认同)
  • 你救了我的屁股.谢谢.如果你想贡献开源,我建议你为jQuery UI方法创建一个补丁:$ .datepicker.iso8601Week(date),因为它只返回weekNo,但没有年份. (4认同)
  • 提供的代码不遵循ISO 8601,它是一个接一个 (2认同)
  • 哎呀你是对的,我的错字,应该是'2015-12-30'有效. (2认同)

小智 34

你也可以使用momentjs库:

moment().format('W')

  • 或者'moment().week()` (9认同)

ora*_*eis 23

顺便提一下http://javascript.about.com/library/blweekyear.htm

Date.prototype.getWeek = function() {
    var onejan = new Date(this.getFullYear(),0,1);
    var millisecsInDay = 86400000;
    return Math.ceil((((this - onejan) /millisecsInDay) + onejan.getDay()+1)/7);
};
Run Code Online (Sandbox Code Playgroud)

  • 我认为,因为这被添加到原型中,所以你可以期待,因为Date将星期日视为第一天. (3认同)

nvd*_*nvd 21

如上所述但没有上课:

let now = new Date();
let onejan = new Date(now.getFullYear(), 0, 1);
week = Math.ceil( (((now - onejan) / 86400000) + onejan.getDay() + 1) / 7 );
Run Code Online (Sandbox Code Playgroud)

  • 这个问题询问了 ISO 8601,这忽略了。作为问题的答案,它完全是错误的 (7认同)
  • @havlock是的,但这是谷歌上“用 JavaScript 获取一年中的一周”的第一个结果,因此它可以帮助很多人(不需要接受的答案的复杂性) (4认同)
  • 一简堂!\ *忍者卷\ * (2认同)

Bra*_*och 10

Jacob Wright的Date.format()库以PHP的date()函数风格实现日期格式化,并支持ISO-8601周数:

new Date().format('W');
Run Code Online (Sandbox Code Playgroud)

仅仅一周的数字可能有点矫枉过正,但它确实支持PHP样式格式化,如果你要做很多这样的事情,它会非常方便.


Dmi*_*okh 6

getWeekOfYear: function(date) {
        var target = new Date(date.valueOf()),
            dayNumber = (date.getUTCDay() + 6) % 7,
            firstThursday;

        target.setUTCDate(target.getUTCDate() - dayNumber + 3);
        firstThursday = target.valueOf();
        target.setUTCMonth(0, 1);

        if (target.getUTCDay() !== 4) {
            target.setUTCMonth(0, 1 + ((4 - target.getUTCDay()) + 7) % 7);
        }

        return Math.ceil((firstThursday - target) /  (7 * 24 * 3600 * 1000)) + 1;
    }
Run Code Online (Sandbox Code Playgroud)

以下代码与时区无关(使用UTC日期),并根据https://en.wikipedia.org/wiki/ISO_8601工作


小智 6

获取任何给定日期的周数

function week(year,month,day) {
    function serial(days) { return 86400000*days; }
    function dateserial(year,month,day) { return (new Date(year,month-1,day).valueOf()); }
    function weekday(date) { return (new Date(date)).getDay()+1; }
    function yearserial(date) { return (new Date(date)).getFullYear(); }
    var date = year instanceof Date ? year.valueOf() : typeof year === "string" ? new Date(year).valueOf() : dateserial(year,month,day), 
        date2 = dateserial(yearserial(date - serial(weekday(date-serial(1))) + serial(4)),1,3);
    return ~~((date - date2 + serial(weekday(date2) + 5))/ serial(7));
}
Run Code Online (Sandbox Code Playgroud)

例子

console.log(
    week(2016, 06, 11),//23
    week(2015, 9, 26),//39
    week(2016, 1, 1),//53
    week(2016, 1, 4),//1
    week(new Date(2016, 0, 4)),//1
    week("11 january 2016")//2
);
Run Code Online (Sandbox Code Playgroud)


Bal*_*rtl 5

我发现Oracle 规范中描述的 Java SE 的SimpleDateFormat类很有用:http: //goo.gl/7MbCh5。就我而言,Google Apps 脚本的工作原理如下:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), "GMT", "w"));
  Logger.log(weekNum);
}
Run Code Online (Sandbox Code Playgroud)

例如,在电子表格宏中,您可以检索文件的实际时区:

function getWeekNumber() {
  var weekNum = parseInt(Utilities.formatDate(new Date(), SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone(), "w"));
  Logger.log(weekNum);
}
Run Code Online (Sandbox Code Playgroud)


thd*_*oan 5

下面的代码计算正确的 ISO 8601 周数。它date("W")在 1/1/1970 和 1/1/2100 之间每周匹配 PHP 。

/**
 * Get the ISO week date week number
 */
Date.prototype.getWeek = function () {
  // Create a copy of this date object
  var target = new Date(this.valueOf());

  // ISO week date weeks start on Monday, so correct the day number
  var dayNr = (this.getDay() + 6) % 7;

  // ISO 8601 states that week 1 is the week with the first Thursday of that year
  // Set the target date to the Thursday in the target week
  target.setDate(target.getDate() - dayNr + 3);

  // Store the millisecond value of the target date
  var firstThursday = target.valueOf();

  // Set the target to the first Thursday of the year
  // First, set the target to January 1st
  target.setMonth(0, 1);

  // Not a Thursday? Correct the date to the next Thursday
  if (target.getDay() !== 4) {
    target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
  }

  // The week number is the number of weeks between the first Thursday of the year
  // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
  return 1 + Math.ceil((firstThursday - target) / 604800000);
}
Run Code Online (Sandbox Code Playgroud)

资料来源: Taco van den Broek


如果您不想扩展原型,那么这里有一个函数:

function getWeek(date) {
  if (!(date instanceof Date)) date = new Date();

  // ISO week date weeks start on Monday, so correct the day number
  var nDay = (date.getDay() + 6) % 7;

  // ISO 8601 states that week 1 is the week with the first Thursday of that year
  // Set the target date to the Thursday in the target week
  date.setDate(date.getDate() - nDay + 3);

  // Store the millisecond value of the target date
  var n1stThursday = date.valueOf();

  // Set the target to the first Thursday of the year
  // First, set the target to January 1st
  date.setMonth(0, 1);

  // Not a Thursday? Correct the date to the next Thursday
  if (date.getDay() !== 4) {
    date.setMonth(0, 1 + ((4 - date.getDay()) + 7) % 7);
  }

  // The week number is the number of weeks between the first Thursday of the year
  // and the Thursday in the target week (604800000 = 7 * 24 * 3600 * 1000)
  return 1 + Math.ceil((n1stThursday - date) / 604800000);
}
Run Code Online (Sandbox Code Playgroud)

示例用法:

getWeek(); // Returns 37 (or whatever the current week is)
getWeek(new Date('Jan 2, 2011')); // Returns 52
getWeek(new Date('Jan 1, 2016')); // Returns 53
getWeek(new Date('Jan 4, 2016')); // Returns 1
Run Code Online (Sandbox Code Playgroud)