JavaScript:将日/周转换为年

标签 javascript function date dayofweek week-number

我已经使用 Stack Overflow 几个月了,但这是我的第一篇文章。

我需要一个函数来将周数和星期几转换为 dd/mm/yyyy 格式。

我必须使用的日期值格式为 day/weekNumber。例如:3/43 转换为 20XX 年 10 月 24 日星期三。年份值将是当前年份。

日期值从 1(星期一)开始。

我在网上找到了很多函数(例如 thisthisthis )。有些使用 ISO 8601 日期,我认为这对我不起作用。我还没有找到适合我的。

提前致谢

最佳答案

这个解决方案确实需要添加一个额外的库,但我认为这是非常值得的。这是一个 momentjs用于操作日期和时间的库。它得到积极维护并且有很好的documentation .一旦您获得了 day 和 weekNumber 的值(在我们的例子中是 3 和 43),您应该执行以下操作:

function formatInput(day, weekNumber){

    var currentDate = moment(new Date());     // initialize moment to a current date
    currentDate.startOf('year');              // set to Jan 1 12:00:00.000 pm this year
    currentDate.add('w',weekNumber - 1);      // add number of weeks to the beginning of the year (-1 because we are now at the 1st week)
    currentDate.day(day);                     // set the day to the specified day, Monday being 1, Sunday 7

    alert(currentDate.format("dddd, MMMM Do YYYY"));  // return the formatted date string 
    return currentDate.format("dddd, MMMM Do YYYY");
}

我认为这个库以后可能对您有用,并且在日期和时间操作以及格式化选项方面有很多可能性。还有一个为 momentjs 编写的很棒的文档。

关于JavaScript:将日/周转换为年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13045572/

相关文章:

javascript - JS - 如何将Image对象变成灰度并显示

javascript - 显示完整日期而不仅仅是 hh :ss in LightningChart JS? 的方法

python - 具有自动换行功能的 Python 文字处理函数

mysql - 创建查询以按 2 个字段获取未完成调用组的计数

php - mysql php 不同日期年份

javascript - 使用alertify.js 进行递归会导致自动关闭警报

javascript - 从深层链接的开头删除/#/?

通过多行模式匹配的函数声明

css - SCSS 可复用函数

c# - PHP 等效于 C# ticks