iamkun / dayjs

⏰ Day.js 2kB immutable date-time library alternative to Moment.js with the same modern API
https://day.js.org
MIT License
46.72k stars 2.28k forks source link

use format("YYYY/wo") to get the wrong Value #2274

Open selye opened 1 year ago

selye commented 1 year ago

Describe the bug 通过 locale("zh-cn").format('YYYY/wo')进行格式化的时候,23年1月1号显示为2023年52周,显示有问题。 https://codesandbox.io/s/objective-wildflower-539cvn?file=/src/App.js

Expected behavior A clear and concise description of what you expected to happen. 期望得到22年第52周

Information

Summer-Shen commented 8 months ago

Similar issue here -- not sure if this is related to how week numbers work together with weekStart +1,不知道这是否与 weekStartweek() 的影响有关

const dayjs = require("dayjs");
const weekOfYear = require("dayjs/plugin/weekOfYear");
const updateLocale = require("dayjs/plugin/updateLocale");
const advancedFormat = require("dayjs/plugin/advancedFormat");

dayjs.extend(weekOfYear);
dayjs.extend(updateLocale);
dayjs.extend(advancedFormat);

dayjs.updateLocale("zh-cn", {
  weekStart: 7, // week starts at Sunday
});

function parseDateToWeekNumber(date) {
  return dayjs(date).locale("zh-cn").format("YYYY-wo");
}

console.log(parseDateToWeekNumber("2025-12-31")); // 2025-1st
console.log(parseDateToWeekNumber("2026-01-01")); // 2026-1st
Summer-Shen commented 7 months ago

@selye

Workaround: use gggg instead of YYYY, see docs for more details. 解决方法:使用 gggg 代替 YYYY,详情参见 文档

const dayjs = require("dayjs");
const weekOfYear = require("dayjs/plugin/weekOfYear");
const updateLocale = require("dayjs/plugin/updateLocale");
const advancedFormat = require("dayjs/plugin/advancedFormat");
const weekYear = require("dayjs/plugin/weekYear");

dayjs.extend(weekOfYear);
dayjs.extend(updateLocale);
dayjs.extend(advancedFormat);
dayjs.extend(weekYear);

dayjs.updateLocale("zh-cn", {
  weekStart: 7, // week starts at Sunday
});

function parseDateToWeekNumberWithWeekYear(date) {
  return dayjs(date).locale("zh-cn").format("gggg-wo");
}

console.log(parseDateToWeekNumberWithWeekYear("2025-12-31")); // 2026-1st
console.log(parseDateToWeekNumberWithWeekYear("2026-01-01")); // 2026-1st