Everything You Need to Know About Date in JavaScript
JavaScript's Date objects are often confusing that we turn to libraries (such as Date-fns and Moment) whenever we need to deal with dates and times.
But we don't always need libraries. If you know what to pay attention to, Date can actually be very simple. In this article, I will walk you through all about the Date object.
First, let us acknowledge the existence of time zones.
Time zone
There are hundreds of time zones in the world. In JavaScript, we only care about two things - local time and coordinated Universal Time (UTC).
- Local time refers to the time zone where your computer is located.
- UTC is synonymous with Greenwich Mean Time (GMT) in practice.
By default, almost all date methods in JavaScript (except one) provide date/time for local time. You can only get UTC when you specify UTC.
With these we can discuss creation dates.
Creation date
You can create dates using new Date()
. There are four possible ways to use new Date()
:
- Use date string
- Use date parameters
- Use timestamp
- Without parameters
Date String Method
In the date string method, you can create a date by passing the date string to new Date
.
1 |
|
We tend to use date string methods when writing dates. This is natural because we have been using date strings all our lives.
If I wrote 21-03-1988, you wouldn't have any questions that it was March 21, 1988. Right? But if you write 21-03-1988 in JavaScript, you get Invalid Date
.
This has a good reason.
We interpret date strings differently in different parts of the world. For example, 11-06-2019 may be June 11, 2019 or November 6, 2019. But you can't be sure which one I'm referring to unless you know the date system I'm using.
In JavaScript, if you want to use a date string, you need to use a format that is accepted worldwide. One of these formats is the ISO 8601 extended format.
1 |
|
Here is what the value means:
- YYYY: 4-digit years
- MM: 2-digit months (01 in January, 12 in December)
- DD: 2-digit date (0 to 31)
- -: Date Separator
- T: Indicates the beginning of time
- HH: 24-digit hours (0 to 23)
- mm: minutes (0 to 59)
- ss: seconds (0 to 59)
- sss: milliseconds (0 to 999)
- :: Time separator
- Z: If Z exists, the date will be set to UTC. If Z does not exist, it is local time. (This only applies to cases where time is provided.)
If you are creating a date, hours, minutes, seconds, and milliseconds are optional. So if you want to create a date for June 11, 2019, you can write this:
1 |
|
Please pay special attention to this. There is a big problem in creating dates using date strings. If you console.log
this date, you can find the problem.
If you live in an area behind GMT, you will get a date displayed as June 10.
If you live in an area leading to GMT, you will get a date displayed as June 11.
This happens because the date string method has a special behavior: if you create a date (not specifying a time), you get a date set to UTC.
In the above case, when you write new Date('2019-06-11')
, the date you actually created was June 11, 2019, at 12 am UTC. That's why people living in areas behind GMT get June 10 instead of June 11.
If you want to create a date at local time using the date string method, you need to include the time. When including time, you need to write at least HH and mm (otherwise Google Chrome will return an invalid date).
1 |
|
The entire local time with the UTC problem with using date strings can be a source of difficult to catch errors. Therefore, I recommend that you do not use date strings to create dates.
(By the way, MDN warns not to use date string methods, as browsers may parse date strings in different ways).
If you want to create a date, use a parameter or a timestamp.
Create date with parameters
You can pass in up to seven parameters to create a date/time.
- Year: 4-digit year.
- Month: Month (0-11). Months start from scratch. If omitted, the default is 0.
- Date: Date in the month (1-31). If omitted, the default is 1.
- Hour: hours of the day (0-23). If omitted, the default is 0.
- Minutes: Minutes (0-59). If omitted, the default is 0.
- Seconds: Seconds (0-59). If omitted, the default is 0.
- Milliseconds: milliseconds (0-999). If omitted, the default is 0.
1 |
|
Many developers (myself included) avoid using parameter methods because it looks complicated. But it's actually very simple.
Try to read the numbers from left to right. From left to right, you insert values in decreasing amplitude: year, month, day, hour, minute, second, and millisecond.
1 2 3 4 5 6 7 8 9 |
|
The most problematic part of Date is that the month value starts from zero, i.e. January === 0, February === 1, March === 2, and so on.
It's a bit strange that JavaScript starts from scratch (apparently because Java does that), but rather than arguing why January should be 1 (rather than 0), it's better to accept that months in JavaScript start from scratch. Once you accept this fact, the date becomes easier to process.
Here are some more examples for you to familiar with:
1 2 3 4 5 6 7 8 9 |
|
Note that the dates created using parameters are all local time?
This is one of the added benefits of using parameters – you won't confuse local time and UTC. If you need UTC, you can create dates in UTC this way:
1 2 |
|
Create dates with timestamps
In JavaScript, the timestamp is the number of milliseconds that pass from January 1, 1970 (January 1, 1970 is also known as Unix epoch time). In my experience, you rarely use timestamps to create dates. You only use timestamps to compare different dates (more on this later).
1 2 |
|
Without parameters
If you create a date without any parameters, you get the date set to the current time (local time).
1 |
|
You can see from the image that when I write this, Singapore time is May 25, 2019 at 11:10 am.
Summary of creation date
- You can create dates using
new Date()
. - There are four possible syntaxes:
- Use date string
- Usage parameters
- Use timestamp
- Without parameters
- Never use the date string method to create a date.
- It is best to use parameter methods to create dates.
- Remember (and accept) that the months in JavaScript start from scratch.
Next, let's talk about converting dates to readable strings.
Format date
Most programming languages provide formatting tools to create any date format you want. For example, in PHP, you can write date("d MY")
as a date similar to 23 Jan 2019.
But there is no easy way to format dates in JavaScript.
The native Date object comes with seven formatting methods. Each of these seven methods gives you a specific value (and they are very useless).
1 |
|
-
toString
provides you with Wed Jan 23 2019 17:23:42 GMT 0800 (Singapore Standard Time) -
toDateString
provides you with Wed Jan 23 2019 -
toLocaleString
provides you with 23/01/2019, 17:23:42 -
toLocaleDateString
provides you with 23/01/2019 -
toGMTString
provides you with Wed, 23 Jan 2019 09:23:42 GMT -
toUTCString
provides you with Wed, 23 Jan 2019 09:23:42 GMT -
toISOString
provides you with 2019-01-23T09:23:42.079Z
If you need a custom format, you need to create it yourself.
Write a custom date format
Suppose you want something like Thu, 23 January 2019. To create this value, you need to understand (and use) the date method that comes with the Date object.
To get dates, you can use these four methods:
-
getFullYear
: Get 4-digit years based on local time -
getMonth
: Get the month (0-11) based on local time. Months start from scratch. -
getDate
: Get the date in the month based on local time (1-31). -
getDay
: Get the day of the week (0-6) based on local time. The day of the week begins on Sunday (0) and ends on Saturday (6).
Creating 23 and 2019 for Thu, 23 January 2019 is simple. We can use getFullYear
and getDate
to get them.
1 2 3 |
|
Getting Thu and January is difficult.
To get January, you need to create an object that maps all twelve-month values to their respective names.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Since the month starts from zero, we can use arrays instead of objects. It produces the same result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
To get January you need:
- Use
getMonth
to get the month starting from the date. - Get month name from
months
1 2 3 |
|
Abbreviation version:
1 2 |
|
You do the same with Thu. This time, you need an array containing seven days a week.
1 2 3 4 5 6 7 8 9 |
|
then you:
- Use
getDay
to getdayIndex
- Use
dayIndex
to getdayName
1 2 |
|
Abbreviation version:
1 |
|
You then combine all the variables you created to get the formatted string.
1 2 |
|
Yes, it's cumbersome. But once you get the trick, it is impossible.
If you need to create a custom format, you can use the following methods:
-
getHours
: Get hours (0-23) based on local time. -
getMinutes
: Get minutes (0-59) based on local time. -
getSeconds
: Get seconds (0-59) based on local time. -
getMilliseconds
: Get milliseconds (0-999) based on local time.
Next, let's talk about comparing dates.
Compare dates
If you want to know if one date is earlier or later than another, you can compare them directly with >, = and <.>
1 2 3 4 5 6 7 8 |
|
To check if two dates happen to fall at the same time, you can check their timestamps using getTime
.
1 2 3 4 5 6 7 |
|
If you want to check if both dates are on the same day, you can check their getFullYear
, getMonth
and getDate
values.
1 2 3 4 5 6 7 |
|
There is one more thing we must introduce.
Get dates from another date
There are two possible scenarios where you need to get the date from another date.
- Set a specific date/time value from another date.
- Add/subtract increments from another date.
Set a specific date/time
You can set a date/time from another date using these methods:
-
setFullYear
: Sets a 4-digit year at local time. -
setMonth
: Set the month at local time. -
setDate
: Sets the date in the month at local time. -
setHours
: Set the hours at local time. -
setMinutes
: Set minutes at local time. -
setSeconds
: Set seconds at local time. -
setMilliseconds
: Set milliseconds at local time.
For example, if you want to set the date to the 15th day of the month, you can use setDate(15)
.
1 2 3 4 |
|
If you want to set the month to June, you can use setMonth
. (Remember, months in JavaScript start from scratch!)
1 2 3 4 |
|
Note: The above setting method changes the original date object. In practice, we should not change the object (the reason is explained in detail here). We should do these operations on the new date object.
1 2 3 4 5 |
|
Add/subtract increments from another date
Increment is change. Adding/subtracting increments from another date means: You want to get a date with a distance of X from another date. It can be X years, X months, X days, etc.
To get the increment, you need to know the value of the current date. You can get it using the following method:
-
getFullYear
: Get 4-digit years based on local time -
getMonth
: Get the month (0-11) based on local time. -
getDate
: Get the date in the month based on local time (1-31). -
getHours
: Get hours (0-23) based on local time. -
getMinutes
: Get minutes (0-59) based on local time. -
getSeconds
: Get seconds (0-59) based on local time. -
getMilliseconds
: Get milliseconds (0-999) based on local time.
There are two common ways to add/subtract increments. The first method is more popular on Stack Overflow. It is concise and clear, but difficult to understand. The second method is more verbose, but easier to understand.
Let's introduce these two methods.
Suppose you want to get the date three days from today. In this example, we also assume that today is March 28, 2019. (It's easier to explain when we use fixed dates).
The first method (setting method)
// Assume today is March 28, 2019 const today = new Date(2019, 2, 28)
First, we create a new Date object (so we don't change the original date)
1 |
|
Next, we need to know the value we want to change. Since we are changing the date, we can use getDate
to get the date.
1 |
|
We want a date three days later than today. We will add increments (3) to the current date using.
1 |
|
The complete code for setting the method:
1 2 3 4 5 |
|
The second method (new Date method)
Here we use getFullYear
, getMonth
, getDate
and other getter methods until we find the type of the value we want to change. Then we use new Date
to create the final date.
1 2 3 4 5 6 7 8 9 10 |
|
Both methods work. Choose one and stick to it.
Automatic date correction
If you provide Date with values beyond its acceptable range, JavaScript will automatically recalculate the date for you.
Here is an example. Suppose we set the date to March 33, 2019. (There is no March 33 on the calendar). In this case, JavaScript will automatically adjust March 33 to April 2.
1 |
|
This means that when creating increments, you don't have to worry about calculating minutes, hours, dates, months, etc. JavaScript will automatically handle it for you.
1 |
|
This is everything you need to know about JavaScript native Date objects.
More information about Date in JavaScript
- Understand dates and times in JavaScript (DigitalOcean)
- Explore JavaScript Date Objects (Alligator.io)
Interested in learning more JavaScript?
If you find this Date introduction useful, you might like Learn JavaScript, a course I created to teach people everything they need to know about JavaScript.
In this course, I will introduce the basic concepts you need to know and then show you how to use the concepts you have learned to build real-world components.
have a look. You may find it useful.
Also, if you have any JavaScript issues, please feel free to contact me. I will try my best to create a free article to answer your questions.
The above is the detailed content of Everything You Need to Know About Date in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

In this week's roundup of platform news, Chrome introduces a new attribute for loading, accessibility specifications for web developers, and the BBC moves

Two articles published the exact same day:

This is me looking at the HTML element for the first time. I've been aware of it for a while, but haven't taken it for a spin yet. It has some pretty cool and

The first part of this two-part series detailed how we can get a two-thumb slider. Now we'll look at a general multi-thumb case, but with a different and

GooFonts is a side project signed by a developer-wife and a designer-husband, both of them big fans of typography. We’ve been tagging Google

The document head might not be the most glamorous part of a website, but what goes into it is arguably just as important to the success of your website as its
