Search code examples
javascriptfunctiondatedayofweekweek-number

JavaScript: Convert Day/Week Into Year


I have been using Stack Overflow for a number of months now, but this is my first post.

I require a function to convert a week number and and day of week into a dd/mm/yyyy format.

The date values i have to work with are in the format day/weekNumber. So for example: 3/43 converts to Wednesday 24 October 20XX. The year value will be the current year.

The day value starts at 1 (Monday).

I have found lots of functions on the internet (such as this, this and this). Some work with ISO 8601 dates, which i do not think will work for me. And i have not yet found one that works for me.

Thanks in advance,


Solution

  • This solution does require an extra library to be added, but I think it is really worth it. It is a momentjs library for manipulating dates and time. It is actively maintained and has a great documentation. Once you get the values for day and weekNumber (in our case 3 and 43), you should do as follows:

    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");
    }
    

    I think this library might be useful to you later on and there are plenty of possibilities regarding date and time manipulation, as well as formatting options. There is also a great documentation written for momentjs.