JavaScript Date Set Methods: A Practical Guide for Developers

Java Script @ Freshers.in

JavaScript Date objects are fundamental in handling and manipulating dates and times in web development. While Get methods allow you to retrieve date and time components, Set methods enable you to modify these components. Understanding these Set methods is crucial for dynamic date manipulation, such as setting deadlines, scheduling events, or creating calendars.

JavaScript Date Set Methods

Each Set method in JavaScript allows for precise control over date and time settings:

setFullYear(year[, month[, day]])

Description: Sets the full year (and optionally, month and day) of the date object.

Example:

let date = new Date();
date.setFullYear(2024, 5, 20); // Sets date to June 20, 2024
console.log(date);

setMonth(month[, day])

Description: Sets the month (and optionally, the day) for a date object. Months are zero-indexed.

Example:

let date = new Date();
date.setMonth(0, 1); // Sets date to January 1 of the current year
console.log(date);

setDate(day)

Description: Sets the day of the month for a date object.

Example:

let date = new Date();
date.setDate(15); // Sets the day of the month to 15
console.log(date);

setHours(hours[, minutes[, seconds[, ms]]])

Description: Sets the hours (and optionally minutes, seconds, and milliseconds).

Example:

let date = new Date();
date.setHours(13, 30, 15, 500); // Sets time to 1:30:15.500 PM
console.log(date);

setMinutes(minutes[, seconds[, ms]])

Description: Sets the minutes (and optionally seconds and milliseconds).

Example:

let date = new Date();
date.setMinutes(45, 30, 200); // Sets minutes to 45, seconds to 30, and milliseconds to 200
console.log(date);

setSeconds(seconds[, ms])

Description: Sets the seconds (and optionally milliseconds).

Example:

let date = new Date();
date.setSeconds(30, 500); // Sets seconds to 30 and milliseconds to 500
console.log(date);

setMilliseconds(ms)

Description: Sets the milliseconds for a date object.

Example:

let date = new Date();
date.setMilliseconds(750); // Sets milliseconds to 750
console.log(date);

setTime(milliseconds)

Description: Sets the Date object to the time represented by a number of milliseconds since January 1, 1970, UTC.

Example:

let date = new Date();
date.setTime(1670000000000); // Sets date to a specific timestamp
console.log(date);

Get more articles on Java Script

Author: user