Table of Contents
Time zone
Creation date
Date String Method
Create date with parameters
Create dates with timestamps
Without parameters
Summary of creation date
Format date
Write a custom date format
Compare dates
Get dates from another date
Set a specific date/time
Add/subtract increments from another date
The first method (setting method)
The second method (new Date method)
Automatic date correction
More information about Date in JavaScript
Interested in learning more JavaScript?
Home Web Front-end CSS Tutorial Everything You Need to Know About Date in JavaScript

Everything You Need to Know About Date in JavaScript

Apr 20, 2025 am 10:09 AM

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() :

  1. Use date string
  2. Use date parameters
  3. Use timestamp
  4. Without parameters

Date String Method

In the date string method, you can create a date by passing the date string to new Date .

1

new Date('1988-03-21')

Copy after login

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

<code>// ISO 8601 扩展格式`YYYY-MM-DDTHH:mm:ss.sssZ`</code>

Copy after login

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

new Date('2019-06-11')

Copy after login

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

new Date('2019-06-11T00:00')

Copy after login

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.

  1. Year: 4-digit year.
  2. Month: Month (0-11). Months start from scratch. If omitted, the default is 0.
  3. Date: Date in the month (1-31). If omitted, the default is 1.
  4. Hour: hours of the day (0-23). If omitted, the default is 0.
  5. Minutes: Minutes (0-59). If omitted, the default is 0.
  6. Seconds: Seconds (0-59). If omitted, the default is 0.
  7. Milliseconds: milliseconds (0-999). If omitted, the default is 0.

1

// June 11, 2019, 5:23:59 am, local time new Date(2019, 5, 11, 5, 23, 59)

Copy after login

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

new Date(2017, 3, 22, 5, 23, 50)

 

// If you follow the left-to-right formula, you can read this date easily.

// Year: 2017,

// Month: April (because the month starts from scratch)

// Date: 22

// Hours: 05

// Minutes: 23

// Seconds: 50

Copy after login

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

// March 21, 1988, at 12 a.m., local time.

new Date(1988, 2, 21)

 

// December 25, 2019, 8 am, local time.

new Date(2019, 11, 25, 8)

 

// November 6, 2023, 2:20 am, local time new Date(2023, 10, 6, 2, 20)

 

// June 11, 2019, 5:23:59 am, local time new Date(2019, 5, 11, 5, 23, 59)

Copy after login

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

// June 11, 2019, at 12 am, UTC.

new Date(Date.UTC(2019, 5, 11))

Copy after login

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

// June 11, 2019, 8:00 am (on my local time, Singapore)

new Date(1560211200000)

Copy after login

Without parameters

If you create a date without any parameters, you get the date set to the current time (local time).

1

new Date()

Copy after login

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

  1. You can create dates using new Date() .
  2. There are four possible syntaxes:
    1. Use date string
    2. Usage parameters
    3. Use timestamp
    4. Without parameters
  3. Never use the date string method to create a date.
  4. It is best to use parameter methods to create dates.
  5. 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

const date = new Date(2019, 0, 23, 17, 23, 42)

Copy after login
  1. toString provides you with Wed Jan 23 2019 17:23:42 GMT 0800 (Singapore Standard Time)
  2. toDateString provides you with Wed Jan 23 2019
  3. toLocaleString provides you with 23/01/2019, 17:23:42
  4. toLocaleDateString provides you with 23/01/2019
  5. toGMTString provides you with Wed, 23 Jan 2019 09:23:42 GMT
  6. toUTCString provides you with Wed, 23 Jan 2019 09:23:42 GMT
  7. 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:

  1. getFullYear : Get 4-digit years based on local time
  2. getMonth : Get the month (0-11) based on local time. Months start from scratch.
  3. getDate : Get the date in the month based on local time (1-31).
  4. 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

const d = new Date(2019, 0, 23)

const year = d.getFullYear() // 2019

const date = d.getDate() // 23

Copy after login

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

const months = {

  0: 'January',

  1: 'February',

  2: 'March',

  3: 'April',

  4: 'May',

  5: 'June',

  6: 'July',

  7: 'August',

  8: 'September',

  9: 'October',

  10: 'November',

  11: 'December'

}

Copy after login

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

const months = [

  'January',

  'February',

  'March',

  'April',

  'May',

  'June',

  'July',

  'August',

  'September',

  'October',

  'November',

  'December'

]

Copy after login

To get January you need:

  1. Use getMonth to get the month starting from the date.
  2. Get month name from months

1

2

3

const monthIndex = d.getMonth()

const monthName = months[monthIndex]

console.log(monthName) // January

Copy after login

Abbreviation version:

1

2

const monthName = months[d.getMonth()]

console.log(monthName) // January

Copy after login

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

const days = [

  'Sun',

  'Mon',

  'Tue',

  'Wed',

  'Thu',

  'Fri',

  'Sat'

]

Copy after login

then you:

  1. Use getDay to get dayIndex
  2. Use dayIndex to get dayName

1

2

const dayIndex = d.getDay()

const dayName = days[dayIndex] // Thu

Copy after login

Abbreviation version:

1

const dayName = days[d.getDay()] // Thu

Copy after login

You then combine all the variables you created to get the formatted string.

1

2

const formatted = `${dayName}, ${date} ${monthName} ${year}`

console.log(formatted) // Thu, 23 January 2019

Copy after login

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:

  1. getHours : Get hours (0-23) based on local time.
  2. getMinutes : Get minutes (0-59) based on local time.
  3. getSeconds : Get seconds (0-59) based on local time.
  4. 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

const earlier = new Date(2019, 0, 26)

const later = new Date(2019, 0, 27)

 

console.log(earlier <p> If you want to check if two dates happen to fall at the same time, it is more difficult to compare. You cannot compare them using == or ===.</p><pre class="brush:php;toolbar:false"> const a = new Date(2019, 0, 26)

const b = new Date(2019, 0, 26)

 

console.log(a == b) // false

console.log(a === b) // false

Copy after login

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

const isSameTime = (a, b) => {

  return a.getTime() === b.getTime()

}

 

const a = new Date(2019, 0, 26)

const b = new Date(2019, 0, 26)

console.log(isSameTime(a, b)) // true

Copy after login

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

const isSameDay = (a, b) => {

  return a.getFullYear() === b.getFullYear() &&

    a.getMonth() === b.getMonth() &&

    a.getDate() === b.getDate()

}

 

const a = new Date(2019, 0, 26, 10) // January 26, 2019, 10:00 am const b = new Date(2019, 0, 26, 12) // January 26, 2019, 12:00 noon console.log(isSameDay(a, b)) // true

Copy after login

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.

  1. Set a specific date/time value from another date.
  2. Add/subtract increments from another date.

Set a specific date/time

You can set a date/time from another date using these methods:

  1. setFullYear : Sets a 4-digit year at local time.
  2. setMonth : Set the month at local time.
  3. setDate : Sets the date in the month at local time.
  4. setHours : Set the hours at local time.
  5. setMinutes : Set minutes at local time.
  6. setSeconds : Set seconds at local time.
  7. 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

const d = new Date(2019, 0, 10)

d.setDate(15)

 

console.log(d) // January 15, 2019

Copy after login

If you want to set the month to June, you can use setMonth . (Remember, months in JavaScript start from scratch!)

1

2

3

4

const d = new Date(2019, 0, 10)

d.setMonth(5)

 

console.log(d) // June 10, 2019

Copy after login

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

const d = new Date(2019, 0, 10)

const newDate = new Date(d)

newDate.setMonth(5)

 

console.log(d) // January 10, 2019 console.log(newDate) // June 10, 2019

Copy after login

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:

  1. getFullYear : Get 4-digit years based on local time
  2. getMonth : Get the month (0-11) based on local time.
  3. getDate : Get the date in the month based on local time (1-31).
  4. getHours : Get hours (0-23) based on local time.
  5. getMinutes : Get minutes (0-59) based on local time.
  6. getSeconds : Get seconds (0-59) based on local time.
  7. 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

const finalDate = new Date(today)

Copy after login

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

const currentDate = today.getDate()

Copy after login

We want a date three days later than today. We will add increments (3) to the current date using.

1

finalDate.setDate(currentDate 3)

Copy after login

The complete code for setting the method:

1

2

3

4

5

const today = new Date(2019, 2, 28)

const finalDate = new Date(today)

finalDate.setDate(today.getDate() 3)

 

console.log(finalDate) // March 31, 2019

Copy after login

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

const today = new Date(2019, 2, 28)

 

// Get the required value const year = today.getFullYear()

const month = today.getMonth()

const day = today.getDate()

 

// Create a new Date (with increments)

const finalDate = new Date(year, month, day 3)

 

console.log(finalDate) // March 31, 2019

Copy after login

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

// March 33 => April 2 new Date(2019, 2, 33)

Copy after login

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

// March 33 => April 2 new Date(2019, 2, 30 3)

Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

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

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

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

Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Apr 17, 2025 am 10:55 AM

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

The Deal with the Section Element The Deal with the Section Element Apr 12, 2025 am 11:39 AM

Two articles published the exact same day:

Some Hands-On with the HTML Dialog Element Some Hands-On with the HTML Dialog Element Apr 16, 2025 am 11:33 AM

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

Multi-Thumb Sliders: General Case Multi-Thumb Sliders: General Case Apr 12, 2025 am 10:52 AM

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

How We Tagged Google Fonts and Created goofonts.com How We Tagged Google Fonts and Created goofonts.com Apr 12, 2025 pm 12:02 PM

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

It's All In the Head: Managing the Document Head of a React Powered Site With React Helmet It's All In the Head: Managing the Document Head of a React Powered Site With React Helmet Apr 15, 2025 am 11:01 AM

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

See all articles