Search code examples
javascriptnode.jsdate-formatstring-to-datetime

Convert string to date and get Day


How to convert string Date to Date?

I have a string "20210712" in the format yyyymmdd how to convert it into date...And how to get the day of It.


Solution

  • You can use String.substr to split the date string into its components. We'll use the + shorthand to convert each component into a number, then create a new Date object from it, using the Date constructor new Date(year, monthIndex, day).

    NB: In JavaScript we pass the monthIndex to the Date rather than the month number, so July is represented as monthIndex = 6;

    To get the day of the month from your date, you'll need Date.getDate().

    To get the day of the week from your date, you'll need Date.getDay(), this will return 0 - 6 (Sunday (0) -> Saturday (6))

    To get the day of the week as a string from your date, you can use Intl.DateTimeFormat, this will return 'Monday' -> 'Sunday'.

    const timestamp = "20210712";
    const year = +timestamp.substr(0,4);
    const monthIndex = +timestamp.substr(4,2) - 1;
    const day = +timestamp.substr(6,2);
    
    console.log("Timestamp:", timestamp)
    console.log("Date components:", JSON.stringify({ year, monthIndex, day }))
    
    const date = new Date(year ,monthIndex, day);
    console.log('Date:', date.toDateString());
    console.log('Day of Month:', date.getDate());
    
    // Sunday - Saturday : 0 - 6
    console.log('Day of Week (0-6):', date.getDay());
    console.log('Day of Week (string):', new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(date))