Home  >  Article  >  Web Front-end  >  The most detailed explanation of Date in JavaScript

The most detailed explanation of Date in JavaScript

黄舟
黄舟Original
2017-03-07 15:01:08973browse

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