In JavaScript, the Date object is a built-in object that allows you to work with dates and times. It provides a variety of methods to handle dates, compare them, manipulate them, and format them.
The Date object in JavaScript represents a single point in time. It provides various functionalities to work with dates and times like creating a Date object in several ways, and it allows you to perform operations like extracting parts of the date (year, month, day), comparing dates, and manipulating dates.
Creating a Date Object
You can create a Date object in multiple ways. Below are some of the most common methods:
1. Using the Default Date() Constructor
The default constructor creates a Date object representing the current date and time.
JavaScript
const now = new Date();
console.log(now);
Output2025-01-16T04:25:58.204Z
- new Date() creates a Date object for the current date and time.
- console.log(now) prints the current date and time to the console.
2. Using a specific date string
You can pass a date string to the constructor to create a Date object for a specific date and time.
JavaScript
const specificDate = new Date("2023-12-25T10:00:00");
console.log(specificDate);
Output2023-12-25T10:00:00.000Z
- new Date(“2023-12-25T10:00:00”) creates a date for December 25, 2023, at 10:00 AM.
- console.log(specificDate) shows the date and time: “2023-12-25T10:00:00”.
3. Using Year, Month, and Other Parameters
The Date constructor can also take individual parameters for year, month (0-indexed), day, hour, minute, second, and millisecond.
JavaScript
const anotherDate = new Date(2023, 11, 25, 10, 0, 0);
console.log(anotherDate);
Output2023-12-25T10:00:00.000Z
- new Date(2023, 11, 25, 10, 0, 0) creates a Date object for December 25, 2023, at 10:00 AM (months are 0-indexed, so 11 represents December).
- console.log(anotherDate) outputs the specified date and time: “2023-12-25T10:00:00.000”.
4. Using Timestamps
You can create a Date object from a timestamp (milliseconds since January 1, 1970).
JavaScript
const timestampDate = new Date(1672531200000);
console.log(timestampDate);
Output2023-01-01T00:00:00.000Z
- new Date(1672531200000) creates a Date object based on the number of milliseconds since January 1, 1970 (Unix Epoch).
- console.log(timestampDate) outputs the corresponding date and time for that timestamp, which is “2023-01-01T00:00:00.000Z”.
Getting Date and Time Components
Once you have a Date object, you can easily extract various components like the year, month, day, hours, minutes, and seconds.
JavaScript
let cDate = new Date();
console.log(cDate.getFullYear()); // Gets the current year
console.log(cDate.getMonth()); // Gets the current month (0-indexed)
console.log(cDate.getDate()); // Gets the current day of the month
console.log(cDate.getHours()); // Gets the current hour
console.log(cDate.getMinutes()); // Gets the current minutes
console.log(cDate.getSeconds()); // Gets the current seconds
Note: The getMonth() method returns a zero-indexed value (0 for January, 11 for December).
Date Manipulation
You can perform various date manipulations such as adding or subtracting days, months, or years to/from a specific date.
Adding Days to a Date
JavaScript
let cDate = new Date();
cDate.setDate(cDate.getDate() + 5); // Adds 5 days to the current date
console.log(cDate);
Output2025-02-16T18:36:36.850Z
In this example, we use the setDate() method to add 5 days to the current date.
Comparing Dates
JavaScript also allows you to compare two Date objects to check if they are equal or which one is earlier or later.
JavaScript
let date1 = new Date('2023-12-31');
let date2 = new Date('2024-01-01');
if (date1 < date2) {
console.log('date1 is earlier than date2');
} else if (date1 > date2) {
console.log('date1 is later than date2');
} else {
console.log('Both dates are the same');
}
Outputdate1 is earlier than date2
In this example, we compare date1 and date2 using comparison operators like <, >, and ===.
Formatting Dates
JavaScript provides various methods to format dates into a human-readable string, although formatting options can be limited in plain JavaScript. You can use toLocaleDateString() or toLocaleTimeString() to format dates and times.
Formatting a Date to a Local String
JavaScript
let now = new Date();
let formattedDate = now.toLocaleDateString('en-US');
console.log(formattedDate); // Output format: MM/DD/YYYY
The toLocaleDateString() method allows you to specify a locale (e.g., ‘en-US’ for American English) and formats the date accordingly.
Formatting Date and Time
JavaScript
let now = new Date();
let formattedDateTime = now.toLocaleString('en-US');
console.log(formattedDateTime); // Output format: MM/DD/YYYY, HH:MM:SS AM/PM
Output2/11/2025, 6:41:41 PM
The toLocaleString() method returns both the date and time in a localized format.
UTC Methods
In JavaScript, Date objects are based on the local time zone. However, you can use the UTC methods to handle date and time in Coordinated Universal Time (UTC).
JavaScript
let now = new Date();
console.log(now.getUTCFullYear()); // Gets the current year in UTC
console.log(now.getUTCMonth()); // Gets the current month (0-indexed) in UTC
console.log(now.getUTCDate()); // Gets the current day of the month in UTC
The getUTC*() methods return the corresponding date components in UTC.
Date Parsing
JavaScript’s Date object allows you to parse date strings into Date objects.
JavaScript
let dateS = '2023-12-31';
let parsed = new Date(dateS);
console.log(parsed);
Output2023-12-31T00:00:00.000Z
You can also parse date strings in various formats such as ‘YYYY-MM-DD’, ‘MM/DD/YYYY’, or even ISO 8601 date strings.
Date Object Method’s Table
Here are some methods that define the usage of a Date object, These are non-static methods.
Below methods are returns all the values according to local time
| Method | Description |
|---|
| Date() | It returns presents day’s date and time. |
| getDate() | It returns the day for the specified date. |
| getDay() | It returns the day of the week for the specified date. |
| getFullYear() | It returns the year of the specified date. |
| getYear() | This method returns the year in the specified date. |
| getHours() | It returns the hour in a specified date. |
| getMilliseconds() | It returns the milliseconds in the specified date. |
| getMinutes() | It returns the minutes in the specified date. |
| getMonth() | It returns the month in the specified date. This also find the month. |
| getSeconds() | This method returns the seconds in the specified date. |
| getTime() | This method returns the date in terms of numeric value as milliseconds. |
| setDate() | This method sets the day of the month for a specified date. |
| setFullYear() | This method sets the full year for a specified date. |
Below methods are returns all the values according to universal time
Conclusion
The JavaScript Date object is a powerful tool for working with dates and times. By understanding its methods and properties, you can handle a wide variety of date-related tasks in your applications. For more advanced date manipulation and formatting, consider using external libraries to complement the built-in functionality.
Similar Reads
Rashi/Zodiac Chart: Know Your Rashi by Name and Date Of Birth
The Indian astrology system recognizes 12 Rashis or Zodiac Signs, each with distinct characteristics. The Moon sign, determined by the Moon's placement at birth, is crucial in Vedic Astrology. Understanding Zodiac Signs helps individuals discover their personality traits, compatibility, and what the
13 min read
100+ Happy Birthday Wishes: Sweet Quotes & Message ideas
Birthday is the most important day in anyone's life. So wishing your friends, relatives, or colleagues a Happy birthday will make the bond super strong. We have crafted the Top 100 Happy Birthday wishes that you can share on the eve with your friends, partner, or any colleague. Happy Birthday Wishes
14 min read
15 Best IPTV Service Providers Subscriptions (Top Picks)
Finding a reliable IPTV service provider can be challenging with so many options available. As streaming becomes the new standard for entertainment, IPTV services have gained huge popularity by offering a wide variety of TV channels, on-demand content, and international programmingâall through an in
14 min read
Best Free Movie Download Sites for 2024
Want to watch a movie whenever you want? Simply download it to your device and watch it later, even if you don't have an internet connection. This is called "streaming it locally." The best part about downloading a movie is that it's always ready for you, no matter where you are! Most legal movie do
9 min read
6 Best ChatGPT Plugin for Summarizing YouTube Videos Quickly
Presenting the best ChatGPT plugin for YouTube summary that will transform media consumption. Gathering important ideas from long YouTube videos in a world full of information can be intimidating. It reduces intricate information into a brief synopsis, enabling you to quickly assimilate the main poi
9 min read
ChatGPT Tips & Tricks: 5 Secret Tips That Can Boost Your ChatGPT Game to God Mode
Are you one of those folks who've tried using ChatGPT but ended up feeling a bit frustrated? Well, let us tell you, you're not alone in this sad situation. Whether you're a student or a tech whiz working in IT, ChatGPT has been a helpful companion for everyone! But the thing is, not everyone knows h
7 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. JavaScript is an interpreted language that executes code line by line providing more flexibility. HTML adds Structure to a web page, CSS st
11 min read
IPTV España: Los 10 Mejores Proveedores de Listas IPTV en España
En España, IPTV se ha consolidado como la opción preferida de muchos usuarios en España. En 2025, encontrar los mejores proveedores de listas de IPTV se ha convertido en una tarea crucial para disfrutar de una experiencia televisiva excepcional. Este artÃculo explora el universo de IPTV España, desg
10 min read
How to Download and Install the Google Play Store
The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed? In this step-by-step guide, youâll learn how to safely download and instal
6 min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read