DEV Community

loading...

Custom util to get weekday name or number

Mehul Lakhanpal
Full stack Developer | Micro-blogging on Web Development at codedrops.tech | Creator of File Ops, Note Box, GitHub Marker
Originally published at codedrops.tech ・1 min read
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

Discussion (2)

Collapse
stegriff profile image
Stephen 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
318097 profile image
Mehul Lakhanpal Author

Great i did not know that. Thanks 😀