gpt4 book ai didi

javascript - 时刻.js : Get first day of first week by given year

转载 作者:行者123 更新时间:2023-11-30 07:20:52 25 4
gpt4 key购买 nike

我试图在给定的那一天得到第一周的第一天

正确的结果:

2017 = 2 Jan (Monday)

2016 = 4 Jan (Monday)

2015 = 1 Jan (Thursday)

2014 = 1 Jan (Wednesday)

2013 = 1 Jan (Tuesday)

我可以通过以下方式获得一年的第一天:

moment().year(year).startOf('year') // All result is 1. jan XXXX

然后我试了:(正确)

moment().day(1).year(2017).week(1) // 2 Jan (Monday) (correct)

但当改为 2016 时:(错误)

moment().day(1).year(2016).week(1) // 10 Jan (Sunday) (wrong)

有人知道如何获得正确的结果吗? (我对纯 JS date() 也开放)

PS:周数基于 Norway

Playground : https://jsfiddle.net/6sar7eb4/

最佳答案

无需使用循环,您可以使用 week() 简单地测试周数是否不是 1提供本地化输出

The output of moment#week will depend on the locale for that moment.

您必须使用 locale() 将语言环境设置为 moment获取周开始语言环境感知的方法。如果你必须用英文显示结果,你可以 change locale locally .

这里是一个工作示例:

function getFirstDayOfFirstWeekByYear( year ) {
// Create moment object for the first day of the given year
let func = moment({year:year})
// Check if 1st of January is in the first week of the year
if( func.week() !== 1 ){
// If not, add a week to the first day of the current week
func.startOf('week').add(1, 'week');
}
// Return result using english locale
return func.locale('en').format('D. MMMM YYYY (dddd)')
}

// Set Norwegian Bokmål locale globally
moment.locale('nb');

// Tester
[2017, 2016, 2015, 2014, 2013].forEach(function ( year ) {
let s = '<li>' + getFirstDayOfFirstWeekByYear( year ) + '</li>'
document.getElementsByTagName('BODY')[0].innerHTML += s
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment-with-locales.min.js"></script>

关于javascript - 时刻.js : Get first day of first week by given year,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44846953/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com