typescript – get the day name from a date

I tried to get the day name from a date, but with the date 27/02/2021 i get Invalid Date

new Date(exam.examDate).toLocaleString('fr-FR', { weekday: 'long' })

i tried to convert the date using datePipe but it return the below error

Unable to convert "27/02/2021" into a date’ for pipe ‘DatePipe

new Date(this.datePipe.transform(exam.examDate, "dd/MM/yyyy")).toLocaleString('fr-FR', { weekday: 'long' })

7 thoughts on “typescript – get the day name from a date”

  1. You can get a custom day name from Date like:

    let names = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    let dayName = names[new Date(dateString).getDay()];
  2. This is because Date expects MM/DD/YYYY but you’re passing DD/MM/YYYY:

    const getDay = date => {
      const parts = date.split('/');
      return new Date(+parts[2], +parts[1] - 1, +parts[0]).toString().split(' ')[0]; 
    console.log( getDay('27/02/2021') );

    Using moment.js:

    const getDay = date =>
      moment(date, "DD/MM/YYYY").format('ddd');
    console.log( getDay('27/02/2021') );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
  3. examDate = "27/02/2021";
    date = examDate.split("/");
    x = new Date(date[2], date[1] - 1, date[0]);
    // it prints "samedi"
    console.log(x.toLocaleString('fr-FR', { weekday: 'long' }));

Leave a Comment