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?

Upvotes: 1

Views: 2529

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15530

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))      

Upvotes: 5

sanjay
sanjay

Reputation: 534

function get_day(date){
    let d=new Date(date);
    let days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    let day_index=d.getDay();
    return days[day_index]
    }

let today=new Date();
console.log("today is",get_day(today))

Upvotes: 0

Related Questions