If you are a web developer, you probably have used JavaScript Date objects to manipulate dates and times in your projects. But did you know that JavaScript Date objects can be tricky and confusing to work with? For example, how do you compare two dates, format them in different ways, or add and subtract time intervals?
In this guide, we’ll explore:
- The JavaScript Date object
- Date properties and methods
- How to create, display, format, parse, and manipulate dates and times in JavaScript
- Challenges and solutions for dealing with time zones
- Temporal proposal, which aims to improve the date and time features in JavaScript.
Let’s explore each topic in detail.
JavaScript Date Object
Date()
object is the foundation for working with dates and times in JavaScript.Creating a Date object
Let’s start with a simple date example. To work with dates and times in JavaScript, you need to create a Date object. A Date
object represents a single point in time, measured in milliseconds since January 1, 1970 (UTC)
. There are several ways to create a Date object, depending on the input we have.
For example, you can use the following syntaxes:
// #1. Create a Date object with the current date and time
let currentDate = new Date();
// #2. Create a Date object with a specific date and time
// (year, month, day, hour, minute, second)
let specificDate = new Date(2024, 0, 8, 2, 50, 2);
// #3. Create a Date object from a string
let stringDate = new Date("January 8, 2024 02:50:02");
// #4. Create a Date object from a timestamp
// ( milliseconds since January 1, 1970)
let timestampDate = new Date(1700000000000);
What if you want to create a date with a custom value
instead of getting the user’s current date and time? You can do so by giving the date and time in different date formats.
Let’s make a new date with our custom values:
const date1 = new Date('2023-03-25');
console.log(date1);
// Output: Sat Mar 25 2023 05:30:00 GMT+0530 (India Standard Time)
const date2 = new Date('2023-03-25T11:30:00-07:00');
console.log(date2);
// Output: Sun Mar 26 2023 00:00:00 GMT+0530 (India Standard Time)
const date3 = new Date(2023, 2, 25, 11, 30, 0);
console.log(date3);
// Output: Sat Mar 25 2023 11:30:00 GMT+0530 (India Standard Time)
JavaScript Date object methods and properties
The Date
object has a number of properties
and methods
that you can use to work with dates and times:
JavaScript Date methods
const date = new Date();
console.log(date.getFullYear()); // Output: 2023
console.log(date.getMonth()); // Output: 2 (March is month 2)
console.log(date.getDate()); // Output: 25
console.log(date.getDay()); // Output: 6 (Saturday is day 6)
console.log(date.getHours()); // Output: 11
console.log(date.getMinutes()); // Output: 50
console.log(date.getSeconds()); // Output: 31
console.log(date.getMilliseconds()); // Output: 553
console.log(date.getTime());
// Output: 1679722523432 (time in milliseconds since January 1, 1970)
Displaying JavaScript dates and times
What if you wanted to display the date and time in a user-friendly format? You can use one of the following methods:
- JavaScript toString
- JavaScript date to ISO format using toISOString()
- toLocaleString()
- toLocaleDateString()
- toLocaleTimeString()
- toLocaleString()
// Create a Date object with the current date and time
let currentDate = new Date();
// Display the full date and time in the default format
console.log(currentDate.toString());
// Output: Mon Jan 08 2024 08:33:40 GMT+0530 (India Standard Time)
// Display the date and time in the ISO format
console.log(currentDate.toISOString());
// Output: 2024-01-08T02:50:02.000Z
// Display the date and time in the local format
console.log(currentDate.toLocaleString());
// Output: 1/8/2024, 8:40:55 AM
// Display the date and time in a custom format
console.log(`${currentDate.getFullYear()}
-${currentDate.getMonth() + 1}
-${currentDate.getDate()}
${currentDate.getHours()}
:${currentDate.getMinutes()}
:${currentDate.getSeconds()}`);
// Output: 2024-1-8 8:43:35
Formatting JavaScript Dates and Times
You can use the above listed methods to display the date and time in a variety of formats based on the user’s locale:
const date = new Date();
console.log(date.toLocaleDateString());
// Output: 3/25/2023
console.log(date.toLocaleTimeString());
// Output: 11:17:49 AM
let options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short'
};
console.log(date.toLocaleString('en-US', options))
// Output: Saturday, March 25, 2023 at 11:19:07 AM GMT+5:30
In JavaScript date format yyyy-mm-dd and mm/dd/yyyy
are widely used to display. You can also use libraries such as Moment.js to format dates and times in more advanced ways.
Time zones and daylight saving time (DST)
One of the challenges of working with dates and times in JavaScript is dealing with time zones. A time zone is a region that observes a uniform standard time for legal, commercial, and social purposes. Different time zones have different offsets from the Coordinated Universal Time (UTC)
, which is the primary time standard by which the world regulates clocks and time.
For example, India Standard Time (IST)
is UTC+05:30, while Central European Time (CET)
is UTC+01:00. This means that when it is 2:50 AM in UTC, it is 8:20 AM in IST and 3:50 AM in CET.
To get the time zone in JavaScript, use the getTimezoneOffset()
method, which returns the difference in minutes between time on the local machine and the UTC. Because I am writing this from India, my UTC offset is -330 minutes (UTC+05:30).
const now = new Date();
console.log(now.getTimezoneOffset());
// Output: -330 (UTC+05:30)
You can also use the Intl
object to get a list of time zones that are supported by the user’s browser:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
// Output: Asia/Calcutta
Handling daylight-saving
time changes can be tricky, but JavaScript provides built-in support. When creating a Date
object, JavaScript automatically considers daylight-saving
time changes based on the local time zone.
Parsing and manipulating JavaScript dates
When developing apps, we will not always be dealing with date and time objects. In some cases, we will receive the date and time as strings. Before we can use it, we must first transform it into a date object. Using the Date.parse()
and Date.UTC()
methods, you can parse JavaScript string into dates.
Let’s see how to parse a JavaScript string into a Date
object with examples:
const date1 = Date.parse('2023-03-25T11:30:00-07:00');
console.log(new Date(date1));
// Output: Sun Mar 26 2023 00:00:00 GMT+0530 (India Standard Time)
const date2 = Date.UTC(2023, 2, 25, 11, 30, 0);
console.log(new Date(date2));
// Output: Sat Mar 25 2023 17:00:00 GMT+0530 (India Standard Time)
In real-time applications, you may need to add days to date or subtract dates, or sort dates to determine past or future dates. You can perform that manipulation using the JavaScript methods listed below:
- setDate()
- setMonth()
- setFullYear()
const date = new Date();
date.setDate(date.getDate() + 5);
// Add 7 days to the current date
console.log(date);
// Output: Thu Mar 30 2023 11:26:35 GMT+0530 (India Standard Time)
date.setFullYear(date.getFullYear() + 1);
// Add 1 year to the current date
console.log(date);
// Output: Sat Mar 30 2024 11:26:45 GMT+0530 (India Standard Time)
Using JavaScript instanceof date, you can make sure the object is an instance of the Date() constructor.
Using the Temporal
The Temporal proposal is a new set of APIs that aim to improve the date and time features in JavaScript. It is currently at stage 3 of the TC39 process, which means that it is ready for implementation in browsers and other environments.
The Temporal
proposal introduces several new objects, such as:
- Temporal.Instant
- Temporal.PlainDate
- Temporal.PlainTime
- Temporal.PlainDateTime
- Temporal.ZonedDateTime
- Temporal.Duration
- Temporal.Calendar
These objects offer more functionality and accuracy than the existing Date
object. For example, you can use the following syntaxes:
// Create a Temporal.PlainDate object with a specific date
let temporalDate = Temporal.PlainDate.from({year: 2024, month: 1, day: 8});
// Create a Temporal.PlainTime object with a specific time
let temporalTime = Temporal.PlainTime.from({hour: 2, minute: 50, second: 2});
// Create a Temporal.PlainDateTime object by combining a
// Temporal.PlainDate and a Temporal.PlainTime
let temporalDateTime = Temporal
.PlainDateTime.from({date: temporalDate, time: temporalTime});
// Display the Temporal.PlainDateTime object in the ISO format
console.log(temporalDateTime.toString());
// Output: 2024-01-08T02:50:02
// Add one day to the Temporal.PlainDateTime object
temporalDateTime = temporalDateTime.add({days: 1});
// Convert the Temporal.PlainDateTime object to a
// Temporal.ZonedDateTime object using a time zone and a calendar
let temporalZonedDateTime = temporalDateTime
.toZonedDateTime({timeZone: "Asia/Kolkata", calendar: "iso8601"});
// Display the Temporal.ZonedDateTime object in the local format
console.log(temporalZonedDateTime.toLocaleString());
// Output: 1/9/2024, 8:20:02 AM
Conclusion
In this blog post, you have learned how to create, convert, compare, and format dates in JavaScript using the built-in Date object and its methods. We have also discussed some of the challenges and solutions for dealing with time zones and the Temporal proposal, which aims to improve the date and time features in JavaScript.
We’ve gone over the basics of working with dates and times in JavaScript, such as:
- How to create a Date object with default and custom values.
- If you want to display or format a date and time, you can use the
toLocaleDateString()
,toLocaleTimeString()
, ortoLocaleString()
methods. - Use the
getTimezoneOffset()
method to display the date and time in user time zones and daylight saving time. - Parsing JavaScript strings to dates and manipulating dates using
Date.parse()
andDate.UTC()
methods.
By understanding JavaScript date and time, you’ll be better equipped to handle a variety of scenarios that involve dates and times in your web applications.
I hope that this blog post has been helpful and informative for you.