search
HomeWeb Front-endJS TutorialThe most detailed explanation of Date in JavaScript

Basic Date() I won’t talk about it~ : )

How to get the number of days in a certain month?

I don’t know if anyone has encountered this problem? I think if you have written a date component, you must have this problem. My solution at the time was as follows:

For the following three methods, I used 0 as the month parameter based on the month definition of Date in JS itself. January

The most honest way

const EVERY_MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function getDays(year, month) {
  if (month === 1 && isLeap(year)) return 29;
  return EVERY_MONTH_DAYS[month];
}

is to manually map the number of days in each month. If it is February and a leap year, the number of days +1

Any calendar plug-in for osx written by Amway http://www.php.cn/

Isn’t there a better way? It would be nice if there was no logic for manual mapping and leap year judgment.

A slightly diao way

function getDays(year, month) {
  if (month === 1) return new Date(year, month, 29).getMonth() === 1 ? 29 : 28;
  return new Date(year, month, 31).getMonth() === month ? 31 : 30;
}

We found that the third parameter of new Date() can Greater than the last day of each month that we know, such as:

new Date(2016, 0, 200) //Mon Jul 18 2016 00:00:00 GMT+0800 (CST)

In this way, we will use the characteristics of this JS to use 29 and 31 Two key points to determine whether it is still that month except the last day of that month + 1? (Actually, 28 and 30 are the key points).

A slightly more diao method

function getDays(year, month) {
  return new Date(year, month + 1, 0).getDate();
}

## The third parameter of new Date() is less than 1 What will happen to the value? For example, if we pass 0, we will get the last day of the last month. Of course, there is no problem if we pass a negative number:

new Date(2016, 0, -200) //Sun Jun 14 2015 00:00:00 GMT+0800 (CST)

Date.prototype . Various String

specific document explanations are too lazy to copy for everyone to see. Reference link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

The main purpose here is to popularize the following knowledge with everyone:

GMT (Greenwich Mean Time)

Greenwich Mean Time (also known as Greenwich Mean Time or Greenwich Standard Time, the old translation is Greenwich Mean Time) Time; English: Greenwich Mean Time (GMT) refers to the standard time at the Royal Greenwich Observatory in the suburbs of London, England, because the prime meridian is defined on the longitude passing there.

Since February 5, 1924, the Greenwich Observatory has sent time adjustment information to the world every hour.

Theoretically, noon in Greenwich Mean Time refers to the time when the sun crosses the Greenwich meridian (that is, when it is at its highest point above Greenwich). Due to the uneven motion of the Earth in its elliptical orbit, this time may differ from the actual solar time, with a maximum error of up to 16 minutes.

Because the Earth's daily rotation is somewhat irregular and slowly slowing down, Greenwich Mean Time is no longer used as standard time. The current standard time is Coordinated Universal Time (UTC), which is reported by atomic clocks.

So we also see from the documentation on MDN that the explanation for

toGMTString() is:

Returns a string representing the Date based on the GMT ( UT) time zone. Use toUTCString() instead.

UTC(Universal Standard Time)

Coordinated Universal Time, also known as Universal Standard Time or Universal Coordinated Time, referred to as UTC (from The English "Coordinated Universal Time" / the French "Temps Universel Cordonné") is the most important world time standard. It is based on the atomic time and second, and is as close as possible to Greenwich Mean Time

CST( Beijing time)

Beijing time, China Standard Time, China standard time. In terms of time zone division, it belongs to the East Eighth District, which is 8 hours ahead of Coordinated Universal Time and is recorded as UTC+8.

However, the abbreviation of CST is more confusing because it can represent four different times at the same time:

  • Central Standard Time (USA) UT-6:00

  • Central Standard Time (Australia) UT+9:30

  • China Standard Time UT+8:00

  • Cuba Standard Time UT-4:00

Insert a JS client time in China that is inconsistent with the server time

The summary is, go to the front and back ends When transmitting time, try to use UTC time.

ISO date and time representation method

if ( !Date.prototype.toISOString ) {
  ( function() {

    function pad(number) {
      if ( number < 10 ) {
        return &#39;0&#39; + number;
      }
      return number;
    }

    Date.prototype.toISOString = function() {
      return this.getUTCFullYear() +
        &#39;-&#39; + pad( this.getUTCMonth() + 1 ) +
        &#39;-&#39; + pad( this.getUTCDate() ) +
        &#39;T&#39; + pad( this.getUTCHours() ) +
        &#39;:&#39; + pad( this.getUTCMinutes() ) +
        &#39;:&#39; + pad( this.getUTCSeconds() ) +
        &#39;.&#39; + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) +
        &#39;Z&#39;;
    };

  }() );
}

Through Polyfill we can know how ISO represents time. The most important features are The last digit is "Z" and always represents UTC time.

Additional additions

.valueOf() and .getTime()

.valueOf() functions and .getTime() Same.

This method is usually called inside JavaScript rather than explicitly in the code. What's the meaning? Without

valueOf, the instance of Date cannot be operated.

var obj = Object.create(null);
obj + 1; // Uncaught TypeError: Cannot convert object to primitive value(…)

.toJSON

When I looked at the name of this API directly, I thought it would return a string in JSON format, but in fact it is Such a thing

new Date().toJSON() // "2016-05-05T06:03:28.130Z"

actually is like this

JSON.stringify(new Date()) // ""2016-05-05T06:06:02.615Z""

The result can be Parse?

JSON.parse(JSON.stringify(new Date())) // "2016-05-05T06:19:24.766Z"
JSON.parse(&#39;"&#39; + new Date().toJSON() + &#39;"&#39;) // "2016-05-05T06:19:24.766Z"

But the result is just a string. You need to hand this string over to

new Date().

.toLocaleFormat()

does not belong to any standard. Implemented in JavaScript 1.6. It seems that only Firefox supports this API. In fact, the correct approach is to use

.toLocaleDateString()

.toLocale various String()

.toLcale various Strings (locales [, options]])

妈的这个 API 有点烦,看 MDN 的文档你就知道。这个 API 是用来本地化时间的。

这里稍微说下我对这些参数的理解:

locales

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US

// US English uses month-day-year order
alert(date.toLocaleString("en-US"));
// → "12/19/2012, 7:00:00 PM"

// British English uses day-month-year order
alert(date.toLocaleString("en-GB"));
// → "20/12/2012 03:00:00"

// Korean uses year-month-day order
alert(date.toLocaleString("ko-KR"));
// → "2012. 12. 20. 오후 12:00:00"

// Arabic in most Arabic speaking countries uses real Arabic digits
alert(date.toLocaleString("ar-EG"));
// → "٢٠‏/١٢‏/٢٠١٢ ٥:٠٠:٠٠ ص"

// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
alert(date.toLocaleString("ja-JP-u-ca-japanese"));
// → "24/12/20 12:00:00"

// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
alert(date.toLocaleString(["ban", "id"]));
// → "20/12/2012 11.00.00"

locales所指的地区的时区和语言输出。

options

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

  • localeMatcher 选择本地匹配的什么算法,似乎没什么大用

  • timeZone 再设置下 UTC 时区

  • hour12 是否12小时制

  • formatMatcher 各日期时间单元的格式化

    • weekday Possible values are "narrow", "short", "long".

    • era Possible values are "narrow", "short", "long".

    • year Possible values are "numeric", "2-digit".

    • month Possible values are "numeric", "2-digit", "narrow", "short", "long".

    • day Possible values are "numeric", "2-digit".

    • hour Possible values are "numeric", "2-digit".

    • minute Possible values are "numeric", "2-digit".

    • second Possible values are "numeric", "2-digit".

    • timeZoneName Possible values are "short", "long".

栗子:

var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

date.toLocaleString("en-US", {hour12: false}); // "12/19/2012, 19:00:00"

var options = {timeZoneName:&#39;long&#39;,weekday: "long", year: "2-digit", month: "narrow", day: "numeric"};
date.toLocaleString("en-US", options); // "Thursday, D 20, 12, China Standard Time"

插一个JavaScript 显示 Y-m-d H:i:s 的日期时间格式

老实的方法

let date = new Date();
let result = [
  [
    date.getFullYear(),
    date.getMonth() + 1,
    date.getDate()
  ].join(&#39;-&#39;),
  [
    date.getHours(),
    date.getMinutes(),
    date.getSeconds()
  ].join(&#39;:&#39;)
].join(&#39; &#39;).replace(/\b\d\b/g, &#39;0$&&#39;);

diao 一点的方法

var date = new Date();
var result = date.toLocaleString(&#39;zh-CN&#39;, { hour12: false })
  .replace(/\//g, &#39;-&#39;).replace(/\b\d\b/g, &#39;0$&&#39;);

一些有用的时间库

  • https://github.com/moment/moment

  • https://github.com/rmm5t/jquery-timeago

 以上就是关于JavaScript 的 Date 最详细解读的内容,更多相关内容请关注PHP中文网(www.php.cn)!



Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),