JavaScript Date Object
JavaScript’s Date object handles dates and times. JavaScript’s Timers, setTimeout() and setInterval(), schedule code to run after a delay or at intervals.
Date Object Methods
The Date object is a built-in class that offers management methods and holds date and time data.
The new Date() constructor offers multiple methods for creating a Date object:
- new Date(): Using the current date and time, a Date object is created using the new Date() function.
- new Date(milliseconds): The new Date(milliseconds) function generates a Date object by counting the milliseconds that have elapsed since January 1, 1970, at 00:00:00 UTC.
- new Date(dateString): Parses a date expression in a string to create a Date object.
- new Date(year, month, day, hours, minutes, seconds, ms): new Date(year, month, day, hours, minutes, seconds, ms). The month and year are necessary; the others are not. Zero indexing applies to the month (0 for January, 11 for December).
Dates in JavaScript are internally represented as milliseconds from January 1, 1970, at 00:00:00 UTC. A timestamp is another name for this data.
Various getter and setter methods can be used to access and change certain aspects of a Date object. Both local time and Coordinated Universal Time (UTC) versions are available for the majority of procedures.
Common getter methods include:
- getFullYear(): Gets the full year.
- getMonth(): Gets the month (0-11).
- getDate(): Gets the day of the month (1-31).
- getDay(): Gets the day of the week (0 for Sunday, 6 for Saturday). This is read-only.
- getHours(): Gets the hour (0-23).
- getMinutes(): Gets the minute (0-59).
- getSeconds(): Gets the second (0-59).
- getMilliseconds(): Gets the millisecond (0-999).
- getTime(): Returns the timestamp (milliseconds since epoch) for the date object.
Common setter methods include:
- setFullYear(year): Sets the year.
- setMonth(month): Sets the month.
- setDate(day): Sets the day of the month.
- setHours(hour): Sets the hour.
- setMinutes(minute): Sets the minute.
- setSeconds(second): Sets the second.
- setMilliseconds(ms): Sets the milliseconds.
- setTime(milliseconds): Sets the date using a timestamp.
Date objects are modified by set methods. An autocorrection feature in the Date object automatically corrects values that are out of range.
Date.now() is a static function that can be used to obtain the current timestamp without first establishing a Date object.
You can convert a Date object to a string in various formats:
- toString().
- toISOString(): Uses the ISO-8601 format and UTC.
- toLocaleString(): Uses locale-sensitive formatting.
- toLocaleDateString(): Gets the date portion using local time.
- toLocaleTimeString(): Gets the time portion using local time.
- toDateString(): Gets the date portion.
- toGMTString() (deprecated, use toUTCString()).
A common operation is calculating the difference between two dates by subtracting their millisecond representations.
let today = new Date(); // Current date and time
console.log(“Today:”, today.toLocaleString()); // Output date and time string
let xmas = new Date(today.getFullYear(), 11, 25); // Christmas this year (month 11 is Dec)
console.log(“Christmas Date:”, xmas.toLocaleDateString()); // Output date string
let nowTimestamp = Date.now(); // Current timestamp in milliseconds
console.log(“Current timestamp:”, nowTimestamp);
// Example: Calculate days until Christmas
let msToday = today.getTime(); // Get timestamp for today
let msXmas = xmas.getTime(); // Get timestamp for Christmas
if (msToday < msXmas) { // Check if Christmas is in the future
let differenceMs = msXmas – msToday; // Difference in milliseconds
let daysLeft = Math.floor(differenceMs / (1000 * 60 * 60 * 24)); // Convert ms to days
console.log(`Only ${daysLeft} days until Christmas!`); // Corrected template literal
} else {
// Handle case where Christmas has passed this year (set year to next year)
let nextXmas = new Date(today.getFullYear() + 1, 11, 25); // Create date for next Christmas
let msNextXmas = nextXmas.getTime(); // Get timestamp
let differenceMs = msNextXmas – msToday; // Difference in milliseconds
let daysLeft = Math.floor(differenceMs / (1000 * 60 * 60 * 24)); // Convert ms to days
console.log(`Only ${daysLeft} days until next Christmas!`); // Corrected template literal
}
let specificDate = new Date(“July 21, 1983 13:25:00”); // Create date from string
specificDate.setHours(14); // Change the hour to 2 PM (24-hour time)
console.log(“Modified specific date:”, specificDate.toLocaleString()); // Output date and time string
Timers (setTimeout, setInterval)
JavaScript utilities for scheduling asynchronous actions actions started now but finished later are available. The two main timer functions are setInterval() and setTimeout(). They are general-purpose even though they are methods of the Window object and are frequently used in web browsers.
- setTimeout(func, delay,…args): Configures a function (func) to run once following a millisecond delay. You can pass optional arguments (…args) to the function. The value returned by setTimeout() is a timer ID.
- setInterval(func, delay,…args): This function schedules the execution of a function (func) at intervals of milliseconds. It gives back a timer ID as well.
With these timer functions, asynchrony is introduced. The callback function is inserted into an event loop queue by the environment when a timer expires, and it is processed when the callstack is empty. When the delay is set to 0 (setTimeout(func, 0)), the callback is instantly added to the queue, but it does not run until the current function execution is complete.
You can cancel a scheduled execution:
- clearTimeout(timerId): The setTimeout() scheduled execution is cancelled by calling clearTimeout(timerId).
- ClearInterval(timerId): Ends the repeated execution that setInterval() has planned.
When it comes to managing intervals, nested setTimeout calls may be more versatile than setInterval. However, the precise delay cannot be guaranteed by scheduling methods. In browsers, nested timers must wait at least 4 milliseconds after the fifth call or for setInterval. The actual delay may increase due to factors like CPU load or the background browser tab.
Similar to other asynchronous mechanisms like events, timers have the ability to provide closures, which let the scheduled function access variables from the scope in which it was generated.
Here are examples using timers:
// Example using setTimeout
let timerId = setTimeout(function() {
console.log(“This runs after a 2-second delay.”);
}, 2000); // 2000 milliseconds = 2 seconds
// We can cancel the timer if needed before it runs
// clearTimeout(timerId);
// Example using setInterval
let intervalId = setInterval(function() {
console.log(“This runs every 1 second.”);
}, 1000); // 1000 milliseconds = 1 second
In JavaScript applications, these built-in Date methods and timer functions are crucial for managing time-related logic and scheduling tasks.