国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

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 .

 new Date('1988-03-21')

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.

 <code>// ISO 8601 擴(kuò)展格式`YYYY-MM-DDTHH:mm:ss.sssZ`</code>

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:

 new Date('2019-06-11')

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).

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

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.
 // June 11, 2019, 5:23:59 am, local time new Date(2019, 5, 11, 5, 23, 59)

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.

 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

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:

 // 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)

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:

 // June 11, 2019, at 12 am, UTC.
new Date(Date.UTC(2019, 5, 11))

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).

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

Without parameters

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

 new Date()

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).

 const date = new Date(2019, 0, 23, 17, 23, 42)
  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.

 const d = new Date(2019, 0, 23)
const year = d.getFullYear() // 2019
const date = d.getDate() // 23

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.

 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'
}

Since the month starts from zero, we can use arrays instead of objects. It produces the same result.

 const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
]

To get January you need:

  1. Use getMonth to get the month starting from the date.
  2. Get month name from months
 const monthIndex = d.getMonth()
const monthName = months[monthIndex]
console.log(monthName) // January

Abbreviation version:

 const monthName = months[d.getMonth()]
console.log(monthName) // January

You do the same with Thu. This time, you need an array containing seven days a week.

 const days = [
  'Sun',
  'Mon',
  'Tue',
  'Wed',
  'Thu',
  'Fri',
  'Sat'
]

then you:

  1. Use getDay to get dayIndex
  2. Use dayIndex to get dayName
 const dayIndex = d.getDay()
const dayName = days[dayIndex] // Thu

Abbreviation version:

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

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

 const formatted = `${dayName}, ${date} ${monthName} ${year}`
console.log(formatted) // Thu, 23 January 2019

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 <.>

 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

To check if two dates happen to fall at the same time, you can check their timestamps using getTime .

 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

If you want to check if both dates are on the same day, you can check their getFullYear , getMonth and getDate values.

 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

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) .

 const d = new Date(2019, 0, 10)
d.setDate(15)

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

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

 const d = new Date(2019, 0, 10)
d.setMonth(5)

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

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.

 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

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)

 const finalDate = new Date(today)

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.

 const currentDate = today.getDate()

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

 finalDate.setDate(currentDate 3)

The complete code for setting the method:

 const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() 3)

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

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.

 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

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.

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

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.

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

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

What is 'render-blocking CSS'? What is 'render-blocking CSS'? Jun 24, 2025 am 12:42 AM

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

How to use Lotties in Figma How to use Lotties in Figma Jun 14, 2025 am 10:17 AM

In the following tutorial, I will show you how to create Lottie animations in Figma. We'll use two colorful designs to exmplify how you can animate in Figma, and then I'll show you how to go from Figma to Lottie animations. All you need is a free Fig

Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Breaking Boundaries: Building a Tangram Puzzle With (S)CSS Jun 13, 2025 am 11:33 AM

We put it to the test and it turns out Sass can replace JavaScript, at least when it comes to low-level logic and puzzle behavior. With nothing but maps, mixins, functions, and a whole lot of math, we managed to bring our Tangram puzzle to life, no J

External vs. Internal CSS: What's the Best Approach? External vs. Internal CSS: What's the Best Approach? Jun 20, 2025 am 12:45 AM

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Does my CSS must be on lower case? Does my CSS must be on lower case? Jun 19, 2025 am 12:29 AM

No,CSSdoesnothavetobeinlowercase.However,usinglowercaseisrecommendedfor:1)Consistencyandreadability,2)Avoidingerrorsinrelatedtechnologies,3)Potentialperformancebenefits,and4)Improvedcollaborationwithinteams.

CSS Counters: A Step-by-Step Tutorial with Examples CSS Counters: A Step-by-Step Tutorial with Examples Jun 12, 2025 am 10:31 AM

CSSCounters is a tool for creating automatic numbers. 1. Basic usage: define and operate counters through counter-reset and counter-increment, such as "SectionX." before h2. 2. Advanced usage: Use nested counters to create complex numbers, such as chapter and section numbers. 3. Notes: Ensure the counter is reset correctly, optimize performance, and simplify counter logic. 4. Best practice: clear naming, define counters in CSS, and use counter-increment and counter-reset reasonably.

CSS Case Sensitivity: Understanding What Matters CSS Case Sensitivity: Understanding What Matters Jun 20, 2025 am 12:09 AM

CSSismostlycase-insensitive,butURLsandfontfamilynamesarecase-sensitive.1)Propertiesandvalueslikecolor:red;arenotcase-sensitive.2)URLsmustmatchtheserver'scase,e.g.,/images/Logo.png.3)Fontfamilynameslike'OpenSans'mustbeexact.

What is Autoprefixer and how does it work? What is Autoprefixer and how does it work? Jul 02, 2025 am 01:15 AM

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

See all articles