Day 12: Classes
Lesson 5: Date()
So why did we bother learning about classes then? Mainly because of the JavaScript Date
class which is very useful and important to understand how to use.
The Date
class is pretty big and involved, it has a lot of instance and class methods. Don't worry though we're not going to do a full deep dive. I'm just going to show you most common use cases.
Like all classes, you get a new Date
by calling it's constructor
Now, while that looks like now
is just a string, it's not. What's happened is that console.log()
has printed out the default human readable date time.
We can prove that it's not just a simple string by calling an instance method on now
. And boy are there a lot of instance methods you can call on a
Date. Here are just a few.
None of these should be a surprise to you. But this one might be.
Probably a bigger number than you were expecting right? Well, this is the number of milliseconds since midnight on January 1st 1970 UTC time. This is called 'Unix Epoch time' and can be thought of as the start of computer time if you like.
Thanks to leap years, leap seconds and time zones, dates and times are one of the biggest headaches in programming. Being able to get a single number timestamp dating back to a universally agreed point in time is very, very useful.
In fact it's common and useful that there is class (static) method to get it without creating a Date first.
If you want to create a Date at a specific date you can do that with by passing a date into your Date constructor.
There's a lot more to dates than this, the best place to learn more about the Date class is the MDN Docs when you need to work with them more.
I mentioned above that dates are hard to work with. Well they are so hard to work with that one of the few things that all developers agree on is, to not work with dates directly yourself if you can help it and instead use a library to handle it all for you.
We won't touch on using external libraries until one of our last lessons but to give you a resource you can come back to, the most commonly used JavaScript libraries are:
- MomentJS (This is no longer maintained, however it's great and will work for years and years to come)
- Luxon
- Day.js
- date-fns
Don't worry about this for now ... which is why it's in a red box after all.