我已经使用 Stack Overflow 几个月了,但这是我的第一篇文章。
我需要一个函数来将周数和星期几转换为 dd/mm/yyyy 格式。
我必须使用的日期值格式为 day/weekNumber
。例如:3/43
转换为 20XX 年 10 月 24 日星期三。年份值将是当前年份。
日期值从 1(星期一)开始。
我在网上找到了很多函数(例如 this 、 this 和 this )。有些使用 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/