JavaScript
Date Manipulation
Programming
Week Start Date
Coding Tutorial

JavaScript - get the first day of the week from current date

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

JavaScript provides a versatile date manipulation using its built-in Date object. A common requirement in many applications is to determine the first day of the week based on a given date. This can be particularly useful in calendar applications, scheduling systems, or data analysis tasks. This article walks through how to achieve this, providing both an understanding of the Date object and practical code examples in JavaScript.

Understanding the Date Object

The Date object in JavaScript represents a single moment in time in a platform-independent format. It contains a number of methods to perform operations such as getting and setting various date and time components.

Key Methods of the Date Object

  • getDay(): Returns the day of the week (0 for Sunday, 1 for Monday, etc.).
  • getDate(): Returns the day of the month (1-31).
  • getMonth(): Returns the month (0-11).
  • getFullYear(): Returns the full year (4-digit).

Getting the First Day of the Week

To find the first day of the week for a given date, you can follow these steps:

  1. Determine the current day of the week using getDay().
  2. Calculate the offset to find the beginning of the week.
  3. Adjust the current date backward by this offset.

Here’s how the implementation looks in JavaScript:

javascript
1function getFirstDayOfWeek(date) {
2  const currentDay = date.getDay(); // 0 (Sunday) - 6 (Saturday)
3  const diff = date.getDate() - currentDay; // Calculate days to first day
4  return new Date(date.setDate(diff)); // Set to first day of week
5}
6
7// Usage
8const today = new Date(); // Assume today is October 3, 2023 (Tuesday)
9const firstDayOfWeek = getFirstDayOfWeek(today);
10console.log(firstDayOfWeek.toDateString());

Handling Different Start Days of the Week

While this example uses Sunday as the first day of the week, different locales might use Monday or another day. Adjusting the start day of the week involves minor modifications:

javascript
1function getFirstDayOfWeek(date, startDay = 0) {
2  const currentDay = date.getDay();
3  const diff = (currentDay < startDay ? 7 : 0) + currentDay - startDay;
4  return new Date(date.setDate(date.getDate() - diff));
5}
6
7// Usage with Monday as first day of the week
8const firstDayMonday = getFirstDayOfWeek(today, 1);
9console.log(firstDayMonday.toDateString());

Table Summary: Key Date Object Methods and Examples

MethodDescriptionExample Usage
getDay()Day of the week (0-6)new Date().getDay() returns 2 for Tuesday
getDate()Day of the month (1-31)new Date().getDate() returns 3 if today is Oct 3
getMonth()Month of the year (0-11)new Date().getMonth() returns 9 for October
getFullYear()Full year (4-digit)new Date().getFullYear() returns 2023 for year 2023

Additional Considerations

Locales and Time Zones

While the above examples work on the assumption of an unspecified locale, JavaScript's Intl.DateTimeFormat can be used to accommodate local time zone specifics and formatting requirements.

javascript
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
const localTimeString = firstDayOfWeek.toLocaleDateString('en-US', options);
console.log(localTimeString);

Handling Edge Cases

Be cautious of edge cases such as time zone shifts and daylight saving time changes. In applications handling dates across regions, libraries such as Moment.js or date-fns can provide additional utilities to handle these considerations.

Conclusion

This article covered the essentials of calculating the first day of the week using JavaScript's Date object. Through understanding the basic methods and operations of the Date object, tailoring code to fit specific locale requirements becomes manageable. Developers can rely on JavaScript's robust date manipulation capabilities to tackle both simple and complex scheduling needs.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.