用 Javascript 显示周数?

新手上路,请多包涵

我有以下代码用于显示当天的名称,后跟一个固定短语。

 <script type="text/javascript">
    <!--
    // Array of day names
    var dayNames = new Array(
    "It's Sunday, the weekend is nearly over",
    "Yay! Another Monday",
     "Hello Tuesday, at least you're not Monday",
     "It's Wednesday. Halfway through the week already",
     "It's Thursday.",
     "It's Friday - Hurray for the weekend",
    "Saturday Night Fever");
    var now = new Date();
    document.write(dayNames[now.getDay()] + ".");
     // -->
</script>

我想做的是将当前周数放在短语后面的括号中。我找到了以下代码:

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

这是取自 http://javascript.about.com/library/blweekyear.htm 但我不知道如何将它添加到现有的 javascript 代码中。

原文由 dannymcc 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 564
2 个回答

只需将它添加到您当前的代码中,然后调用 (new Date()).getWeek()

 <script>
    Date.prototype.getWeek = function() {
        var onejan = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
    }

    var weekNumber = (new Date()).getWeek();

    var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var now = new Date();
    document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>

原文由 laurent 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果您已经在使用 jQuery-UI(特别是日期选择器):

 Date.prototype.getWeek = function () { return $.datepicker.iso8601Week(this); }

用法:

 var myDate = new Date();
myDate.getWeek();

更多信息: UI/Datepicker/iso8601Week

我意识到这不是一个通用的解决方案,因为它会产生依赖性。然而,考虑到 jQuery-UI 的流行,这可能只是简单地适合某些人——就像我一样。


如果你不使用 jQuery-UI 并且无意添加依赖项。您可以复制他们的 iso8601Week() 实现,因为它是用纯 JavaScript 编写的,没有复杂的依赖关系:

 // Determine the week of the year (local timezone) based on the ISO 8601 definition.
Date.prototype.iso8601Week = function () {
  // Create a copy of the current date, we don't want to mutate the original
  const date = new Date(this.getTime());

  // Find Thursday of this week starting on Monday
  date.setDate(date.getDate() + 4 - (date.getDay() || 7));
  const thursday = date.getTime();

  // Find January 1st
  date.setMonth(0); // January
  date.setDate(1);  // 1st
  const jan1st = date.getTime();

  // Round the amount of days to compensate for daylight saving time
  const days = Math.round((thursday - jan1st) / 86400000); // 1 day = 86400000 ms
  return Math.floor(days / 7) + 1;
};

console.log(new Date().iso8601Week());
console.log(new Date("2020-01-01T00:00").iso8601Week());
console.log(new Date("2021-01-01T00:00").iso8601Week());
console.log(new Date("2022-01-01T00:00").iso8601Week());
console.log(new Date("2023-12-31T00:00").iso8601Week());
console.log(new Date("2024-12-31T00:00").iso8601Week());

原文由 corolla 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题