Search code examples
javascriptdatetimepicker

Get day name from date with format dd-mm-yyyy?


I need a way of getting the name of the day e.g Monday, Tuesday from a date with the format of DD-MM-YYYY I am using bootstrap datetimepicker and when i select a date, the value is just in the format DD-MM-YYYY, I can't use getDay() because the format doesn't agree with it.

I also can't use new Date() because i has to be a date selected from a calendar. Not todays date. When I run the following code I get the error:

date.getDay() is not a function.

$('#datepicker').datetimepicker().on('dp.change', function (event) {
        let date = $(this).val();
        let day = date.getDay();
        console.log(day);
      });
```

Anyone any ideas?

Solution

  • Parsing string as-is by Date constructor is strongly discouraged, so I would rather recommend to convert your date string into Date the following way:

    const dateStr = '15-09-2020',
    
          getWeekday = s => {
            const [dd, mm, yyyy] = s.split('-'),
                  date = new Date(yyyy, mm-1, dd)
            return date.toLocaleDateString('en-US', {weekday: 'long'})
          }
          
    console.log(getWeekday(dateStr))