繁体   English   中英

如何在 Javascript 中获取给定年份和星期的月份名称

[英]How to get month name for a given year and week in Javascript

我在 HTML 中有 2 个表单字段,即 Year 和 Week。

一旦用户从下拉列表中选择了年和周,我想显示所选年和周的月份名称。

谁能帮我根据年份和 iso 周数获取月份名称。

例如:如果我选择年份为 2022,周数为 16,则预期的 output 是April作为月份名称。

这应该是一个 function 返回给定年份和星期的月份名称。

下面是我的示例代码。

getMonthName() {
    const year  =  2022;
    const week  = 16;
    console.log(month);
  }

示例: https://codesandbox.io/s/damp-wood-nynj7f?file=/src/app/app.component.ts

  1. 为您的月份创建映射器:
  2. 4 周 = 1 个月,然后将周的输入值转换为数字并除以 4。(示例:16 / 4 === 4)
  3. 结果是你的映射器的关键:months[divided result]

最好的是使用日期库,例如:dayjs、date-fns、moment、luxon 或其他。

const months = {
    1: "January",
    2: "February"
}

changeWeekHandler(e) {
   const week = parseInt(e.target.value)
   const month = Math.ceil(week / 4) // for round number to the upper (example: Math.ceil(0.25) -> 1)
   this[your input field] = months[month]
}

非常有趣的形式。 我想出了这样的解决方案;

我不建议您每月除以 4 周,因为并非所有月份都有 4 周。 但是根据您的输入,您总是可以从几周内知道一年中的哪一天

周数 * 7 = 日数

创建一个方法:

const dateFromDay = (year, day = 1) => {
  const date = new Date(year, 0);
  return new Date(date.setDate(day));
}

// call the method with your inputs

const myDate = edateFromDay(2022,16*7); 
// here you will have the full date 

// if you want just the month then 
myDate.getMonth();

准确满足您的需求:

//Declare months 
  const monthNames = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];
// Declare method for receiving your month name
const dateFromWeek = (year, week = 1) => {
  
  const date = new Date(year, 0);
  return monthNames[new Date(date.setDate(week*7)).getMonth()];
}
//When you use 
dateFromWekk(2020,3); //just write year and week, you will get the name of month

以下将显示给定 ISO 周数和年份的月份名称(缩写形式)。

 function getMonthName(week, year) { let d =new Date(year,0,1+(week-1)*7); d.getUTCDay()<5?d.setUTCDate(d.getUTCDate()-d.getUTCDay()+1):d.setUTCDate(d.getUTCDate()+8-d.getUTCDay()); return (""+d).split(" ")[1]; } console.log(getMonthName(1,2022)); console.log(getMonthName(11,2022)); console.log(getMonthName(16,2022));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM