In JavaScript, formatting dates encompasses altering date representations, modifying the display style of dates, and isolating individual components such as the day or specific time. This capability is crucial for activities such as time zone conversions and presenting dates in a manner that is easy for users to understand. JavaScript offers multiple libraries, including Date-fns and Day.js, along with built-in objects and methods that facilitate the formatting process. Throughout this article, we will explore the various techniques for formatting dates in JavaScript.
What is a Date Object in JavaScript?
JavaScript includes a native object known as Date, which is designed for handling dates and times.
Example
let now = new Date();
console.log(now);
Output:
2025-09-01T08:27:14.498Z
Internally, JavaScript represents dates as the total count of milliseconds that have elapsed since January 1, 1970, Coordinated Universal Time (UTC), also known as Unix Epoch Time.
How to Use the JavaScript Date Object?
In JavaScript, the Date constructor allows you to manipulate date and time. This tool enables you to retrieve today's date or generate a particular date in either the past or the future. If you instantiate it without any parameters, it will provide you with the precise current date and time, along with the relevant timezone information.
1. Getting Today's Date
If your goal is to obtain the current date and time, you can utilize the Date constructor without providing any arguments to it.
Example
let currentDate = new Date();
console.log(currentDate);
Output:
2025-09-01T08:27:50.235Z
This code initializes a Date object that captures the current date, the present time, and information pertaining to your time zone.
2. Setting a Specific Date
When you wish to establish a date, such as an individual’s birth date or a scheduled appointment on a particular day, you can achieve this by supplying a date string to the Date function in the following manner:
Example
let specificDate = new Date('01-14-2025');
console.log(specificDate);
Output:
2025-01-14T00:00:00.000Z
Regardless of how you format it, JavaScript will automatically transform it into its standard representation, encompassing the complete date, time, and your local time zone.
3. Using Date Without new
Here is a fascinating approach: when utilizing Date without the new keyword, as shown below:
Example
let currentDate = Date();
console.log(currentDate);
Output:
Mon Sep 01 2025 08:28:43 GMT+0000 (Coordinated Universal Time)
Utilizing this method will not yield a Date object. Rather, you will receive a simple string that represents the current date and time.
Difference between Date and new Date
| Code | Result |
|---|---|
| New Date() | Create a real Date object. |
| Date() | Just returns a string version of the current date. |
Inbuilt Date Formatting Methods in JavaScript
JavaScript provides several built-in functionalities that allow us to convert a date into a human-readable string. These features are particularly useful when you need to display a date on a website or record it in an aesthetically pleasing format.
Let us look at some of the most useful ones:
1. toDateString
This approach provides only the date, excluding the time, and presents it in a clear and user-friendly format.
Example
let currentDate = new Date();
console.log(currentDate.toDateString());
Output:
Mon Sep 01 2025
It is highly beneficial when you require fast, straightforward data that does not involve clocks or time zones.
2. toISOString
When you require your date to be formatted in a universally accepted standard applicable in APIs and databases, this is the most optimal choice.
Example
let currentDate = new Date();
console.log(currentDate.toISOString());
Output:
2025-09-01T08:29:38.928Z
This format is referred to as ISO 8601. It is ideal for situations where you require consistent date representation across different locations, irrespective of the user’s time zone.
3. toLocaleString
This approach provides you with the complete date and time, adhering to the formatting conventions of your regional or system preferences.
Example
let currentDate = new Date();
console.log(currentDate.toLocaleString());
Output:
9/1/2025, 8:29:55 AM
Depending on where you are in the world, this might show as:
- 08/30/2025, 12:11:36 PM (US)
- 30/08/2025, 12:11:36 (UK)
- 2025/08/30 12:11:36 (Japan)
This is the reason it is referred to as a "locale" string, as it varies according to your geographical location.
4. toLocaleDateString
This function operates similarly to toLocaleString, but it exclusively returns the date without any accompanying time information.
Example
let currentDate = new Date();
console.log(currentDate.toLocaleDateString());
Output:
9/1/2025
This is ideal if your goal is to present a clear date format to the user, tailored to their specific language or country.
How to Get Specific Parts of a Date in JavaScript?
At times, it is unnecessary to retrieve the complete date; you may only require the year, month, or day from a specific date. Fortunately, JavaScript provides us with native methods that allow for the efficient extraction of these components.
Let us take a look at the useful ones:
1. getFullYear
This approach retrieves the four-digit year from a Date object.
Example
let currentDate = new Date();
console.log(currentDate.getFullYear());
Output:
This simply extracts the year, straightforward and uncomplicated. Extremely useful when you need to showcase or contrast different years.
2. getMonth
This particular method provides the current month, but there's an interesting aspect to note: in JavaScript, the month indexing begins at 0 rather than 1. Consequently, January is represented as 0, while December corresponds to 11.
Example
let currentDate = new Date();
console.log(currentDate.toDateString());
console.log(currentDate.getMonth());
Output:
Mon Sep 01 2025
8
Although the current month is September, JavaScript represents it as 8 since the counting starts from 0.
Note: If you want to show the actual number of the month which means 1 to 12 then you can just add 1. console.log(currentDate.getMonth + 1); This will give you 8 for Sept.
- getDate
This function provides the numerical day of the month. For instance, if the specified date is "Sep 1", the output will be 1.
Example
let currentDate = new Date();
console.log(currentDate.getDate());
Output:
This is ideal when you need to determine a particular date, whether for showcasing birthdays, monitoring deadlines, or setting up reminders.
Utilizing these techniques, you have the capability to deconstruct any date into its individual components and employ them in various ways, whether you are developing a calendar, organizing events, or displaying personalized messages.
Customising Date Formats in JavaScript
JavaScript, by default, provides complete date strings; however, if you wish to present the date in a custom format of your choice, several methods are available to achieve that:
1. Using String Concatenation
Consider this process as manually constructing your own date. You gather the individual components of day, month, and year, and then combine them in a way similar to assembling LEGO blocks.
Example
let today = new Date ();
let customDate = `${today.getDate ()}/${today.getMonth () + 1}/${today.getFullYear ()}`;
console.log(customDate);
Output:
1/9/2025
The function getMonth + 1 is utilized since, in JavaScript, the month of January is represented as 0, while December is denoted as 11. Consequently, to reflect the actual month number in a real-world context, we increment the output of the function by 1.
2. Using Intl.DateTimeFormat
If constructing dates manually seems excessive, JavaScript provides a native date formatter that is capable of interpreting international formats.
Example
let today = new Date ();
let formatter = new Intl.DateTimeFormat('hi-IN');
console.log(formatter.format(today));
Output:
9/1/2025
The function Int1.DateTimeFormat('hi-IN') constructs a date formatter that adheres to the date conventions of India, while the .format method utilizes this formatter on your Date object.
You can also modify 'hi-IN' to an alternative such as "en-US" (United States) or "en-UK" (United Kingdom) to automatically adjust the formatting in accordance with regional conventions.
Supported Browsers
- Opera
- Chrome
- Edge
- Internet Explorer
- Safari
Conclusion
This article aims to provide you with insights into managing dates within JavaScript, a crucial skill for processing time-related information, displaying user-friendly timestamps, and developing practical applications like calendars and event organizers, among others.
JavaScript offers a robust Date object that allows for the creation and manipulation of dates. You can retrieve the present date, establish particular dates, and utilize methods such as toDateString, toISOString, toLocaleString, and toLocaleDateString to present dates in understandable or region-specific formats.
For enhanced flexibility, employing custom formatting through string concatenation or utilizing the Int1.DateTimeFormat API provides the ability to personalize the appearance of dates to align with your application’s requirements or the user's geographic location.
Utilizing these tools enhances the process of formatting and presenting dates, resulting in a more intuitive and adaptable approach. This improvement contributes to clearer code comprehension and a more user-friendly experience in your applications.
In JavaScript, the standard date format that is utilized by default is represented in the ISO 8601 format. This format is particularly structured as follows:
YYYY-MM-DDTHH:mm:ss.sssZ
Here’s a breakdown of each component:
- YYYY: Represents the four-digit year.
- MM: Indicates the two-digit month (01 through 12).
- DD: Denotes the two-digit day of the month (01 through 31).
- T: Serves as a separator indicating the start of the time component.
- HH: Stands for the two-digit hour in a 24-hour format (00 through 23).
- mm: Represents the two-digit minutes (00 through 59).
- ss: Indicates the two-digit seconds (00 through 59).
- sss: Represents milliseconds (000 through 999).
- Z: Signifies the timezone offset from UTC (Coordinated Universal Time), with 'Z' indicating zero offset.
As an illustration, a complete date-time string in JavaScript adhering to this format could appear as follows:
2023-10-05T14:30:00.000Z
This string indicates the 5th of October, 2023, at 14:30:00 UTC, with no offset from UTC time.
The standard output format of JavaScript when invoking new Date.toString is as follows:
"Tue Jul 22 2025 17:40:00 GMT +0530 ) (India Standard time)"
- What is the method to format a date in the YYYY-MM-DD structure using JavaScript?
Example
let date = new Date();
let formatted = `${date.getFullYear() } - ${String(date.getMonth() + 1).padStart(2, '0')} - ${String(date.getDate()).padStart(2, '0')}`;
console.log(formatted);
Output:
2025 - 09 - 01
- Is it possible to utilize external libraries for formatting dates?
Yes. Popular libraries include:
- date-fns (modern and lightweight)
- dayjs (compact and simple)
- js (powerful but deprecated)
- What is the toLocaleDateString method used for?
The toLocaleDateString function provides a way to format a date based on a designated locale:
Example
const date = new Date();
console.log(date.toLocaleDateString('en-US'));
console.log(date.toLocaleDateString('en-UK'));
Output:
To obtain the current timestamp in JavaScript, you can make use of the built-in Date object. The Date object provides various methods to work with dates and times. To acquire the current timestamp, you can utilize the getTime method, which returns the number of milliseconds that have elapsed since January 1, 1970, 00:00:00 UTC. Here is how you can do this:
let currentTimestamp = new Date().getTime();
console.log(currentTimestamp);
Alternatively, if you prefer to get the timestamp in seconds instead of milliseconds, you can divide the result by 1000:
let currentTimestampInSeconds = Math.floor(Date.now() / 1000);
console.log(currentTimestampInSeconds);
In the example above, Date.now is another method that directly returns the current timestamp in milliseconds, which is more concise than creating a new Date object.
By utilizing these methods, you can effectively retrieve the current timestamp in JavaScript for any required application or functionality.
To obtain the current timestamp in JavaScript, you can utilize the following code.
Example
const timestamp = Date.now();
console.log(timestamp);
Output:
1756735461000
- How can you transform a Unix timestamp into a human-readable format?
Example
const timestamp1 = 1756735461000;
const date = new Date(timestamp1);
console.log(date.toString());
Output:
Mon Sep 01 2025 14:04:21 GMT+0000 (Coordinated Universal Time)