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
Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.