Search code examples
javascriptdatetimedate-fns

How to create a JS Date object from weekday and time string


Given a string like Tue:18-20 how can one create a Javascript date object that represents the first/next Tuesday at 18:00 (from now)

For context: Above string format is used to store a users' pick-up and delivery times preferences. Keen to hear if there'd be a better approach to store this (either as a string or different format)


Solution

  • First, write a code to decode your <day>:<startHours>-<endHours> string. Then, You can do it like this

    let day = 1; // Mon : 1, Tue: 2, Wed: 3 ...
    let startHours = 18;
    let endHours= 20;
    
    // get the start of the period
    let dateStart = new Date();
    dateStart.setDate(dateStart.getDate() + (day !== dateStart.getDay() ? (day + 7 - dateStart.getDay()) % 7 : 7));
    dateStart.setHours(startHours, 0, 0, 0)
    console.log(dateStart)
    
    // get the end of the period
    let dateEnd = new Date();
    dateEnd.setDate(dateEnd.getDate() + (day !== dateEnd.getDay() ? (day + 7 - dateEnd.getDay()) % 7 : 7));
    dateEnd.setHours(endHours, 0, 0, 0)
    console.log(dateEnd)