0

I am trying to parse dates in JavaScript with the equivalent of the format %G-%V (e.g., 2020-53, 2021-1, etc.) from Python's datetime library.

My current attempt at doing so is as follows:

getWeek(date_str) {
    var givenDate = new Date(date_str);
    var givenYear = givenDate.getFullYear();
    var startDate = new Date(givenDate.getFullYear(), 0, 1);
    var days = Math.floor((givenDate - startDate) /
        (24 * 60 * 60 * 1000));
    var weekNumber = Math.ceil(days / 7);
    var wkStart = new Date(givenDate.setDate(givenDate.getDate() - givenDate.getDay()));
    var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
    return {"week_num": `${givenYear}-${weekNumber}`, "start_of_week": wkStart, "end_of_week": wkEnd}
}

This seems to be yielding conflicting results around end of year in some cases:

2020-12-27T00:00:00.000Z => 2020-52 (correct)
2020-12-28T00:00:00.000Z => 2020-52 (should be 2020-53)
2020-12-29T00:00:00.000Z => 2020-52 (should be 2020-53)
2020-12-30T00:00:00.000Z => 2020-52 (should be 2020-53)
2020-12-31T00:00:00.000Z => 2020-52 (should be 2020-53)
2021-01-01T00:00:00.000Z => 2020-53 (should be 2020-53)
2021-01-02T00:00:00.000Z => 2021-0  (should be 2020-53)
2021-01-03T00:00:00.000Z => 2021-1  (should be 2020-53)
2021-01-04T00:00:00.000Z => 2021-1  (correct)
OJT
  • 887
  • 1
  • 10
  • 26
  • 1
    Working with dates is still not easy in JS. You might want to have a look at a library like day-fns, luxon, ... if that's not the only date manipulation in your code. – Andreas Jul 29 '22 at 17:08
  • @Andreas any thoughts on a preferred package to do this? I see d3-time-format offers a timeParse function that can utilize those ISO standards... if I were to try to incorporate this into an API would I just require('d3') or something? – OJT Jul 29 '22 at 19:17
  • 1
    Duplicate of [*convert a week number and year to a date object in Javascript*](https://stackoverflow.com/questions/72957624/convert-a-week-number-and-year-to-a-date-object-in-javascript), however since there's no accepted or upvoted answer I can't mark it as a duplicate. You might also read [*Get week of year in JavaScript like in PHP*](https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php), which is the reverse operation but completes the picture. – RobG Jul 30 '22 at 10:25

0 Answers0