DEV Community

Mehul Lakhanpal
Mehul Lakhanpal

Posted on • Originally published at codedrops.tech

Custom util to get weekday name or number

const getDayNameOrNo = (value) => {
  const mappings = [
    [0, "sunday"],
    [1, "monday"],
    [2, "tuesday"],
    [3, "wednesday"],
    [4, "thursday"],
    [5, "friday"],
    [6, "saturday"],
  ];

  const match = mappings.find(
    ([dayNo, name]) => dayNo === value || name === value
  );

  if (!match) return;

  const [matchedNo, matchedName] = match;
  return matchedNo === value ? matchedName : matchedNo;
};

console.log(getDayNameOrNo(0)); // sunday
console.log(getDayNameOrNo("sunday")); // 0
console.log(getDayNameOrNo("friday")); // 5
Enter fullscreen mode Exit fullscreen mode

Thanks for reading 💙

Follow @codedrops.tech for more.

InstagramTwitterFacebook

Micro-Learning ● Web Development ● Javascript ● MERN stack

codedrops.tech


Projects

File Ops - A VS Code extension to easily tag/alias files & quick switch between files

Top comments (2)

Collapse
 
stegriff profile image
Ste Griffiths

Thanks for the post. I think you could improve it by removing the hardcoded English day names and using the JS built-in features to get the day of the week in your locale.

Typescript:

getWeekDays(locale): string[] {
    var baseDate = new Date(Date.UTC(2017, 0, 1)); // just a Sunday
    var weekDays = [];
    for (let i = 0; i < 7; i++) {
      let dayName = baseDate.toLocaleDateString(locale, { weekday: 'long' });
      dayName = dayName[0].toUpperCase() + dayName.slice(1);
      weekDays.push(dayName);
      baseDate.setDate(baseDate.getDate() + 1);
    }
    return weekDays;
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ml318097 profile image
Mehul Lakhanpal

Great i did not know that. Thanks 😀