Javascript Moment.js 根据特定日期(也是过去几年)获取周数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25953551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:08:02  来源:igfitidea点击:

Moment.js get the week number based on a specific day (also past years)

javascriptmomentjsweek-number

提问by Arthur Kovacs

How could I get from moment JS the week number from a date in the past only from a moment formatted object from a day selected?

我如何才能从 JS 时刻仅从所选日期的时刻格式化对象中获取过去某个日期的周数?

回答by Giovani

  $(document).ready(function(){
    var weeknumber = moment("12-25-1995", "MM-DD-YYYY").week();
    console.log(weeknumber);
  });

According momentjs docs:

根据momentjs文档:

Because different locales define week of year numbering differently, Moment.js added moment#week to get/set the localized week of the year.

The week of the year varies depending on which day is the first day of the week (Sunday, Monday, etc), and which week is the first week of the year.

For example, in the United States, Sunday is the first day of the week. The week with January 1st in it is the first week of the year.

因为不同的语言环境定义一年中的周数不同,Moment.js 添加了 moment#week 来获取/设置一年中的本地化周。

一年中的一周取决于哪一天是一周的第一天(星期日、星期一等),哪一周是一年的第一周。

例如,在美国,星期日是一周的第一天。1 月 1 日所在的那一周是一年中的第一周。

So, if you are having problems getting the right week number use .isoWeek()

因此,如果您在获取正确的周数时遇到问题,请使用 .isoWeek()

$(document).ready(function(){
  var weeknumber = moment("11-26-2016", "MMDDYYYY").isoWeek();
  alert(weeknumber);
});

Example

例子

回答by l2aelba

You can also use format()

你也可以使用 format()

Examples:

例子:

moment().format('w') // as .week() like '1'
moment().format('W') // as .isoWeek() like '1'
moment().format('ww') // as .week() (2 digits) like '01'
moment().format('WW') // as .isoWeek() (2 digits) like '01'

ISO Week date: https://en.wikipedia.org/wiki/ISO_week_date

ISO 周日期:https: //en.wikipedia.org/wiki/ISO_week_date

More info:https://momentjs.com/docs/#week-year-week-and-weekday-tokens

更多信息:https : //momentjs.com/docs/#week-year-week-and-weekday-tokens