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

混江龙づ霸主 提交于 2021-01-28 06:27:36

问题


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?

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/63900155/get-day-name-from-date-with-format-dd-mm-yyyy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!