In JavaScript, handling dates and times involves using the Date object, which provides methods for creating and manipulating dates and times. Here's a basic overview:
Creating a Date Object
You can create a new Date
object in several ways:
-
Current Date and Time:
const currentDate = new Date();
-
From a Timestamp (milliseconds since Jan 1, 1970):
const timestampDate = new Date(1620256200000); // Timestamp for May 6, 2021
-
From a Date String:
const dateString = '2021-05-06T12:30:00'; const dateFromString = new Date(dateString);
The Date
object provides methods to get various components of a date and time:
-
getFullYear(), getMonth(), getDate()
: Returns the year, month (0-11), and day (1-31) respectively. -
getHours(), getMinutes(), getSeconds(), getMilliseconds()
: Returns the hour, minute, second, and millisecond respectively. -
getDay()
: Returns the day of the week (0-6, where 0 is Sunday).
You can set various components of a date and time using corresponding setter methods:
-
setFullYear(year), setMonth(month), setDate(day)
: Sets the year, month, and day respectively. -
setHours(hour), setMinutes(minute), setSeconds(second), setMilliseconds(ms)
: Sets the hour, minute, second, and millisecond respectively.
JavaScript doesn't provide built-in formatting methods for dates and times, but you can create your own formatting functions or use libraries like moment.js
or built-in Intl.DateTimeFormat
.
-
Adding/Subtracting Time: Use
setSeconds(), setMinutes(),
etc., or use arithmetic operations on milliseconds. -
Comparing Dates: Use comparison operators (<, >, etc.) or methods like
getTime()
to get the timestamp and compare.
JavaScript Date
objects operate in the local time zone of the user's browser. To work with different time zones, you can either manually adjust the time or use libraries like date-fns or moment-timezone
.
const currentDate = new Date();
console.log(currentDate);
const timestampDate = new Date(1620256200000);
console.log(timestampDate);
const dateString = '2021-05-06T12:30:00';
const dateFromString = new Date(dateString);
console.log(dateFromString);
console.log(currentDate.getFullYear());
console.log(currentDate.getMonth());
console.log(currentDate.getDate());
console.log(currentDate.getHours());
console.log(currentDate.getMinutes());
console.log(currentDate.getSeconds());
currentDate.setFullYear(2022);
console.log(currentDate);
console.log(currentDate < timestampDate);
Understanding JavaScript's date and time functionalities is crucial for building applications that require time-sensitive operations or date manipulations.