简体   繁体   English

使用 Javascript 中的周数从字符串创建日期

[英]Create Date from string with week number in Javascript

I have a string like 2020-44 which contains year and number of the week in the year.我有一个像 2020-44 这样的字符串,其中包含年份和一年中的周数。 Is it possible to create Date object from this string in some easy way?是否可以通过某种简单的方式从该字符串创建 Date object ? Javascripot is able to create dates from string like new Date('2020-12-24'). Javascripot 能够从像 new Date('2020-12-24') 这样的字符串创建日期。 But I would like to use it with format 2020-44.但我想以 2020-44 格式使用它。 Is it possible or not?有没有可能?

This will return the first day of the given week:这将返回给定周的第一天:

 var dateString = "2020-44"; function getDateFromWeek(str) { var y = str.split('-')[0] var w = str.split('-')[1] var d = (1 + (w - 1) * 7); // 1st of January + 7 days for each week return new Date(y, 0, d); } console.log(getDateFromWeek(dateString));

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

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