Extract Date Parts with get Methods
Write a JavaScript function that takes a date string in "YYYY-MM-DD" format, creates a Date object, and returns an object with year, month (1-12), and day properties using getFullYear(), getMonth(), and getDate() methods.
The Date object is JavaScript's built-in type for handling dates and times. Date.prototype.getFullYear() returns the year (4 digits), getMonth() returns the month (0-11, zero-indexed), and getDate() returns the day of the month (1-31). Note that getMonth() returns 0 for January, so you must add 1 for human-readable months.
JavaScript Date objects can be created from date strings in ISO 8601 format ("2024-01-15"), from timestamps (milliseconds since epoch), or from individual date components. The Date API provides both getter and setter methods for each date component, as well as methods for time zones (UTC vs local).
Time complexity is O(1) for parsing and O(1) for each getter method. Space complexity is O(1) for the Date object. The getMonth() method requires adding 1 to convert to human-readable format.
Edge cases include leap years (Feb 29), different month lengths, single-digit months/days, and ensuring the date string is parsed correctly across browsers (YYYY-MM-DD is standard).
Example Input & Output
Christmas 2023
January 15, 2024
Last day of 1999
Millennium
Leap year
Algorithm Flow

Solution Approach
Best Answers
function solution(dateStr) {
var d = new Date(dateStr);
return {
year: d.getFullYear(),
month: d.getMonth() + 1,
day: d.getDate()
};
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
