Use JavaScript to Find the Week Day from a Date

Hero image for Use JavaScript to Find the Week Day from a Date. Image by Behnam Norouzi.
Hero image for 'Use JavaScript to Find the Week Day from a Date.' Image by Behnam Norouzi.

While recently sitting in on a technical interview, our candidate was asked to write a JavaScript/TypeScript function that accepts a date and, by return, determines which day of the week that date falls (or fell) on.

Something like this:

getDayOfWeek('2024-11-01');  // => "Friday"getDayOfWeek('2022-01-01');  // => "Saturday"

In JavaScript, this is a fairly straightforward problem to solve as long as you are familiar with JavaScript's builtin Date object, but what if that wasn't allowed, or that was an area of JavaScript that the candidate wasn't familiar with or didn't know how to use?

Fortunately, we're not that mean during interviews, but it did raise a question that I wanted to explore further...


A simple solution using Date

In JavaScript, we're very fortunate that there is already a builtin method, .getDay() which returns the day of the week as a number (0 for Sunday, 1 for Monday, etc.). So, using this we can create an ordered array of days and use the result of .getDay() as an index.

Here's how I would do it:

const getDayOfWeek = (dateString: string): string => {  const daysOfWeek = [    'Sunday',    'Monday',    'Tuesday',    'Wednesday',    'Thursday',    'Friday',    'Saturday',  ];  const date = new Date(dateString);  const dayIndex = date.getDay();  return daysOfWeek[dayIndex];};

How It Works

  1. We use the Date object to parse the input string, creating a date instance.
  2. .getDay() retrieves the day of the week as an integer.
  3. We then use that integer as an index into the daysOfWeek array, returning the name of the day.

In this way, we get a simple and efficient function which relies upon the native date parsing baked into JavaScript. However, this reliance on the Date object does also introduce a dependency, which means the correctness of our output is totally dependent on the accuracy of Date (no matter how unlikely it might be for that to be incorrect in itself).

It also isn't time zoneindependent; it will return the name of the day in whatever time zone the client is running at the time. That doesn't matter in this particular context, but nevertheless, it's something I'll go into in more detail now.


Time Zones and the Date() Solution

There are two potential issues with this solution relating to time zones, both of them edge cases, but both of them well worth a moment to discuss (and even moreso if you're the candidate in this scenario!)

Date Parsing

Unless the date string you pass into Date specifically includes a time or time zone, JavaScript will assume the local time zone of the user's environment. For example, new Date('20241101') is interpreted as midnight in the local time zone.

What this means is that, depending on the user's time zone, the perceived date could be shifted forwards or backwards around that midday point, potentially altering the calculated day of the week.

Daylight Saving Time (Dst)

Calculating Daylight Saving Time adjustments can be complex, especially if the date passed into our function falls near a time change. However, these shifts usually do not affect the outcome for getDay() as long as the date has been interpreted.

Using Universal Time (Utc) instead

We can avoid these issues by using the UTC methods of the Date object instead. For example, using .getUTCDay() instead of .getDay() will ensure that the day of the week is calculated in Coordinated Universal Time (UTC) rather than the user's local time zone. This is a oneline change in the example solution I've given above: const dayIndex = date.getUTCDay().

If we use this approach, then we can ensure consistent results from our function, regardless of the user's local time zone. Being able to explain this to your interviewer should hopefully gain you a few extra points too!


Another Approach Using Arithmetic and Modulo

An alternative approach would be to manually calculate the day of the week, based on the fact that in the current Gregorian Calendar, 1 January AD 1 was a Monday. We can compute the day of the week for a day by working out the total number of days that have passed since that reference date, and using the modulo operator (%) to determine the remainder when divided by 7. Simple.

Here's what that might look like:

const getDayOfWeekManual = (dateString: string): string => {  const daysOfWeek = [    'Monday',    'Tuesday',    'Wednesday',    'Thursday',    'Friday',    'Saturday',    'Sunday',  ];  const [year, month, day] = dateString.split('-').map(Number);  const isLeapYear = (year: number): boolean =>    (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;  const daysInMonth = (month: number, year: number): number => {    const days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];    return month === 2 && isLeapYear(year) ? 29 : days[month - 1];  };  const totalDays =    Array.from({ length: year - 1 }, (_, i) => i + 1).reduce(      (sum, y) => sum + (isLeapYear(y) ? 366 : 365),      0    ) +    Array.from({ length: month - 1 }, (_, i) => i + 1).reduce(      (sum, m) => sum + daysInMonth(m, year),      0    ) +    day;  const dayIndex = (totalDays - 1) % 7;  return daysOfWeek[dayIndex];};

How It Works

As you might expect, this has a few more moving parts than the first example, but it's still a relatively straightforward process:

  1. We have the same days array as in our previous example.
  2. Parse the Date

    by splitting the input string (YYYYMMDD) into year, month, and day components for processing.
  3. Check for Leap Years

    via a helper function which determines whether a year is a leap year so that we can account for the extra day in February.
  4. Calculate Days in a Month

    : another helper function which returns the number of days in a given month using an array of days per month, and adjusting for February if the year is a leap year.
  5. Sum the days for all years before the input year (adding 366 for leap years, 365 otherwise).
  6. Add the days for all months before the input month in the current year, using daysInMonth.
  7. Add the days in the current month.
  8. Now that we have the total number of days since 1 January AD1 (a Monday), we can divide this by 7 using the modulo operator (% 7). The remainder maps to the correct day of the week (using our days array from point 1).

This approach is totally selfcontained (rather than relying on the Date object) and will work independently of time zone or browser differences because it assumes that a day progresses in a uniform 24hour cycle, unaffected by time zones or daylight saving adjustments.

However, as you can see, it's a much more complex implementation and requires careful handling of leap years and month lengths.


Wrapping up

Both solutions are valid and have their own merits. In an interview scenario, using Date is exactly what I and my colleagues would expect, leveraging native JavaScript capabilities and doing 'enough' to show your understanding of the subject.

The modulobased approach showcases deeper algorithmic thinking and avoids potential pitfalls with time zone handling, although it's also much more complicated and probably totally unnecessary in a realworld use case.


Key Takeaways

  • The Date object's .getDay() method is straightforward but relies on native parsing, but being clientside, it is based on the time zone in the user's environment, which can inadvertently shift the date forward or backwards. You could bypass this by always using Coordinated Universal Time: getUTCDay();
  • It is possible to achieve this manually by using the Gregorian Calendar reference and counting the days. This is a more versatile approach but is also more complex and prone to issues in implementation.

In this case, it boils down to simplicity vs. finite control.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript