Keywords: JavaScript | Date Processing | Week Calculation | Date Object | Time Boundaries
Abstract: This article provides an in-depth exploration of various methods to obtain the first and last day of the current week in JavaScript, including variants starting with Sunday and Monday. Through native Date object manipulation and third-party library comparisons, it thoroughly analyzes the core logic of date calculations, boundary case handling, and best practices. The article includes complete code examples and performance optimization suggestions to help developers master date processing techniques comprehensively.
Fundamentals of Date Calculation
When working with dates in JavaScript, the Date object provides numerous methods for manipulating temporal information. Obtaining the first and last days of the current week requires understanding several key concepts: the current date, the index of the day of the week, and boundary handling for date ranges.
JavaScript's getDay() method returns an integer from 0 to 6, where 0 represents Sunday, 1 represents Monday, and so on up to 6 for Saturday. This index value is central to calculating the week's starting day.
Implementation Starting with Sunday
The implementation using the native Date object is as follows:
var currentDate = new Date();
var firstDayOffset = currentDate.getDate() - currentDate.getDay();
var lastDayOffset = firstDayOffset + 6;
var weekStart = new Date(currentDate.setDate(firstDayOffset));
var weekEnd = new Date(currentDate.setDate(lastDayOffset));This code first retrieves the current date, then calculates the offset between the current date and Sunday. getDate() returns the day of the month, and subtracting getDay() yields the date of Sunday in the current week. Adding 6 days to this result provides the date for Saturday.
Adjustment for Monday as Start
In international applications, it is common to treat Monday as the start of the week. This requires appropriate adjustments to the aforementioned algorithm:
var currentDate = new Date();
var dayOfWeek = currentDate.getDay();
var mondayOffset = currentDate.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1);
var sundayOffset = mondayOffset + 6;
var weekStartMonday = new Date(currentDate.setDate(mondayOffset));
var weekEndSunday = new Date(currentDate.setDate(sundayOffset));The key here is handling the Sunday case. When getDay() returns 0 (Sunday), it is necessary to adjust backward by 6 days to find Monday of the previous week; in other cases, a simple offset calculation suffices.
Time Boundary Handling
In practical applications, precise time boundaries are often required. The original implementation may retain the current time, which can cause issues in certain scenarios. Here is an improved version:
function getWeekRange(startWithMonday) {
var now = new Date();
var start = new Date(now);
var end = new Date(now);
var day = now.getDay();
var diffToStart;
if (startWithMonday) {
diffToStart = day === 0 ? -6 : 1 - day;
} else {
diffToStart = -day;
}
start.setDate(now.getDate() + diffToStart);
start.setHours(0, 0, 0, 0);
end.setDate(start.getDate() + 6);
end.setHours(23, 59, 59, 999);
return { start: start, end: end };
}This implementation ensures that the week start time is set to 00:00:00 and the end time to 23:59:59.999, avoiding ambiguities in time boundaries.
Cross-Month Handling
When the week range crosses month boundaries, JavaScript's Date object automatically handles date adjustments. For example:
var testDate = new Date(2024, 1, 29); // February 29, 2024
var startOffset = testDate.getDate() - testDate.getDay();
var weekStart = new Date(testDate.setDate(startOffset));
// Automatically handles transition from February to MarchThe setDate() method of the Date object intelligently manages month and year rollovers, freeing developers from manually handling these complex boundary cases.
Third-Party Library Solutions
Although native implementations suffice for most scenarios, third-party libraries offer more concise APIs. Using date-fns as an example:
import { startOfWeek, endOfWeek } from 'date-fns';
var now = new Date();
var weekStart = startOfWeek(now, { weekStartsOn: 1 }); // Start with Monday
var weekEnd = endOfWeek(now, { weekStartsOn: 1 });The advantage of third-party libraries lies in cleaner code and built-in internationalization support. However, the cost of additional dependencies must be weighed.
Performance Considerations
In performance-sensitive applications, unnecessary Date object creation should be avoided. Here is an optimized implementation:
function getOptimizedWeekRange(startWithMonday) {
var now = new Date();
var time = now.getTime();
var day = now.getDay();
var msPerDay = 24 * 60 * 60 * 1000;
var startDiff = startWithMonday ?
(day === 0 ? -6 : 1 - day) : -day;
var startTime = time + startDiff * msPerDay;
var endTime = startTime + 6 * msPerDay;
return {
start: new Date(Math.floor(startTime / msPerDay) * msPerDay),
end: new Date(Math.ceil((endTime + 1) / msPerDay) * msPerDay - 1)
};
}This method uses timestamp calculations to avoid multiple Date object operations, offering better performance when executed in loops.
Practical Application Scenarios
Weekly date range calculations are applicable in various contexts:
- Highlighting the current week in calendar components
- Weekly data statistics in reporting systems
- Week views in task management applications
- Weekly attendance records in HR systems
Each scenario may have different requirements for time precision, and developers should choose the appropriate implementation based on specific needs.
Conclusion
Obtaining the first and last days of the current week is a common requirement in JavaScript date processing. By understanding the semantics of the getDay() method and the basic principles of date calculation, various variants can be flexibly implemented. The native Date object provides sufficient capabilities, while third-party libraries offer better development experiences. In actual projects, the choice of solution should be based on performance requirements, internationalization needs, and code maintainability.