It’s a Date

Kevin Neyer
2 min readDec 4, 2020

Using JavaScript’s Date Constructor

Introduction

Over the course of the last week, I was given a React mini code challenge. One of the deliverables was to create a component that returned a live, updating date and time. This, using date and time, was surprisingly a new topic for me. I had an idea of what it should look like, and a quick Google search affirmed those ideas, as well as give me some new information. Today, I want to take a look at these ideas. While the code challenge did ask for the time to update every second, for the purpose of this article, that won’t be covered. Instead, it will be an overview for how to generate the date and time. That said, if you feel like getting snazzy, go on and get those seconds ticking!

The Date Constructor

JavaScript has a date constructor that creates a date instance that represents a single moment in time. As one could imagine it looks something like this:

let date = new Date()

While it can take an argument to establish a specific date, leaving the parenthesis open will create the current date and time.

Console of current date and time

Pretty neat! This is just the start of where things get interesting. By using the date constructor, our date inherits some useful instance methods. Let’s take a look.

Instance Methods

As mentioned, there are quite a few instance methods we inherit. I want to mention the methods I find most useful:
1.) .getDate() => returns the day of the month.
2.) .getFullYear() => returns the four digit representation of the year.
3.) .toDateString() => returns the full date in a readable string format.
4.) .toLocaleDateString() => returns a string version of the date.
5.) .toLocaleTimeString() => returns a string version of the time.

All in all, giving us information that looks like this.

Full console of instance methods

Conclusion

When using JavaScript, it’s pretty cool to know that if we need to get the date or time, we can use a date constructor. There’s also handy instance methods that help isolate the specific information we need. This article is a broad presentation of the things we can do. I highly recommend checking out the MDN docs for further learning. And, as always, happy coding!

--

--