Everything You Need to Know About Dates in JavaScript
Given just 10 days, the creator of JavaScript, Brendan Eich was really short on time while working on the language.
Date handling is fundamental to nearly all programming languages. JavaScript had to have it! Strapped for time, and under orders to “make it like Java”, Eich copied the date object from the existing java.Util.Date
implementation (which was later deprecated). Thus, even today, we’re left with some headaches when dealing with dates.
Nonetheless, displaying the date in a web application can be very useful for a number of reasons. For example, you might want to show a user when they made a purchase or created their account. You might also just want to display the date on your site as a nice reminder for your users.
Whatever the case may be, displaying the date in JavaScript can be a little tricky, unless you know the proper methods. This article will explore those methods, and also introduce you to a little neat interview question at the end of the article.
What are dates in JavaScript?
JavaScript Date
objects represent a point in time in a platform-independent format.
Date
objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the epoch).
There are a few ways to make a date object. The quickest is to make the object for the current date and time.
const date = new Date();
console.log(date);
// Output: Wed Jan 25 2023 10:29:37 GMT-0500 (Eastern Standard Time)
We can also pass in some arguments.
Note: In JavaScript, the months start at 0, just like an array.
We can also add values to the Date
object. We can add a complete date with a string, Date('January 25, 2023 03:24:00');
, pass a year and month, Date(2023, 0);
, and more (see below syntax examples for a complete reference).
const date = new Date(2023, 0, 25);
console.log(date);
// Output: Wed Jan 25 2023 00:00:00 GMT-0500 (Eastern Standard Time)
Syntax Examples
new Date();
new Date(value);
new Date(dateString);
new Date(dateObject);
new Date(year, monthIndex);
new Date(year, monthIndex, day);
new Date(year, monthIndex, day, hours);
new Date(year, monthIndex, day, hours, minutes);
new Date(year, monthIndex, day, hours, minutes, seconds);
new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds);
Date();
That’s a lot, let’s see some examples.
// new Date(year, monthIndex);
const date1 = new Date(2023, 0);
// Output: Sun Jan 01 2023 00:00:00 GMT-0500 (Eastern Standard Time)
// new Date(year, monthIndex, day);
const date2 = new Date(2023, 0, 25);
// Output: Wed Jan 25 2023 00:00:00 GMT-0500 (Eastern Standard Time)
// new Date(year, monthIndex, day, hours);
const date3 = new Date(2023, 0, 25, 23);
// Output: Wed Jan 25 2023 23:00:00 GMT-0500 (Eastern Standard Time)
// new Date(year, monthIndex, day, hours, minutes, seconds, milliseconds);
const date4 = new Date(2023, 0, 25, 23, 10, 10, 10);
// Output: Wed Jan 25 2023 23:10:10 GMT-0500 (Eastern Standard Time)
Date Object Methods
Let’s explore some Date
methods and see how to use them.
toString()
The toString()
method returns a string representing the object.
In the code block above, we logged the date object to the console. To display this in a better way, we can call toString
on the date
variable, like so:
const date = new Date();
console.log(date.toString());
If we log the date
variable with toString()
attached, we’re not going to see the object options. It makes it a bit easier to read.
toDateString()
The toDateString()
method returns the date portion of a Date
object interpreted in the local timezone.
const date = new Date();
console.log(date.toDateString());
// Output: Sun Jan 22 2023
toTimeString()
The toTimeString()
method returns the time portion of a Date
object interpreted in the local timezone.
const date = new Date();
console.log(date.toTimeString());
// Output: 11:42:17 GMT-0500 (Eastern Standard Time)
toUTCString()
toUTCString()
is going to display the date without the timezone, in GMT. toTimeString()
is always going to show the timezone of the browser.
const date = new Date();
console.log(date.toUTCString());
// Output: Wed, 25 Jan 2023 15:52:31 GMT
More Date Methods
In addition to the methods above, we have some other methods at our use. These methods are getFullYear()
, getMonth()
, and getDate()
.
getFullYear()
- returns the year of the specified date, e.g. 2023.getMonth()
- returns the month in the specified date according to local time.getDate()
- returns the day of the month for the specified date.
const date = new Date();
console.log(date.getFullYear());
// Output: 2023
const date1 = new Date();
console.log(date1.getMonth());
// Output: 0
const date2 = new Date();
console.log(date2.getDate());
// Output: 25
A note on Moment.js and other date libraries
Moment.js is deprecated. You shouldn’t use it in new projects. Instead, the creators of Moment.js recommend 5 alternatives:
Check them out and decide which one is best for your next project.
A Date-Based Interview Question
Directions
- Given a
number
variable with value20230122
, convert to a Javascript Date object - Expected result:
2023-01-22T00:00:00.000Z
This question can be a bit tricky. However, try to solve it before moving on to the solution!
Useful links
The solution to this question can be found by using the following links.
Solution
const number = 20230122;
const strNum = number.toString();
const date = new Date(
`${strNum.substring(0, 4)} ${strNum.substring(4, 6)} ${strNum.substring(
6,
8
)}`
);
console.log(date);
Conclusion
If we were to write every single thing about dates in JavaScript, we’d probably have 100 articles by now. Dates in JavaScript isn’t a small topic. Nonetheless, we hope this article taught you some things, and inspired you to learn more about dates in JavaScript.
Looking for a JavaScript developer job? Try Hired!
Related Posts
The Great JavaScript Debate: To Semicolon or Not?
Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.
Read moreHacktoberfest 2024: Get a Free JavaScript Today Sticker
October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.
Read moreCreating a Real Time Chat Application with React, Node, and TailwindCSS
In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.
Read more