The most detailed reading of JavaScript's Date

Source: Internet
Author: User
Tags getdate tojson

The foundation Date() will not say ~:)

How do I get the number of days in a month?

I wonder if you've ever met this question? I think if you had written a date component there must have been this problem, and my solution was this:

The following three methods, month parameter I all according to JS itself for the month definition of Date, with 0 for January

The most honest way.
Const EVERY_MONTH_DAYS = [+, +, +, +, +, +,--]--31];function getDays (year, month) {  if (month = = = 1 && isleap (year)) return;  return every_month_days[month];}

Manually make a map of the number of days per month, if it is February and leap year, that number of days +1

Whatever, Amway, a self-written, OSX calendar plugin Https://github.com/lishengzxc/ng2-calendar

There's no better way to do that? The logic of Manual map and leap year judgment is fine.

A little diao a little way
Function getDays (year, month) {  if (month = = = 1) return new Date (year, Month,). GetMonth () = = = 1? 29:28;  return new Date (year, month, to). GetMonth () = = = Month? 31:30;}

We find that new Date() the third parameter can be greater than the last day of every month we know, for example:

New Date (0,//mon) 00:00:00 gmt+0800 (CST)

In this way, we use this JS feature, with 29 and 31 of the two key points, to determine the last day except that month +1 or that month? (In fact, 28 and 30 are key points).

A little bit more diao way
Function getDays (year, month) {  return new Date (year, month + 1, 0). GetDate ();

new Date()The third parameter is less than 1 of the value will be what happens, such as 0, we have the last month's final day, of course, negative number is no problem:

New Date (0, -200)//sun June 00:00:00 gmt+0800 (CST)
Date.prototype. Various string

Specific document explanation don't bother to copy it to everyone, reference link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Here the main and everyone to popularize the following knowledge:

GMT (Greenwich Normal)

GMT (also known as Greenwich Mean Time or GMT, old to Greenwich Standard Time; English: Greenwich Mean time,gmt) is the standard time for the Royal Greenwich Observatory, located in the outskirts of London, as the prime meridian is defined by the meridians there.

Since February 5, 1924, the Greenwich Observatory has been distributing information to the world on an hourly interval.

In theory, midday at Greenwich Mean time when the Sun crosses the Greenwich Meridian, the highest point over Greenwich. Due to the uneven movement of the Earth in its elliptical orbit, this moment may have an error with the actual sun, with a maximum error of up to 16 minutes.

Since the Earth's daily rotation is somewhat irregular and slows slowly, Greenwich Mean time is no longer used as a standard. The standard time now is the Coordinated Universal Time (UTC), which is produced by atomic clocks.

So we also see from the documentation on MDN that toGMTString() the explanation for this is:

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

UTC (World Standard Time)

Coordinated world time, also known as the world standard Time or the world coordination times, referred to as UTC (from English "coordinated Universal time"/French "temps Universel cordonné"), is the most important world time standard, based on the atomic time of the second, in the moment as close as possible to Greenwich Normal

CST (Beijing Time)

Beijing time, China standards time, Chinese standard times. In the time zone division, belongs to the East eight district, 8 hours earlier than coordinated world time, is recorded as Utc+8.

But this CST abbreviation is more tangled, 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

Plug in a Chinese region JS client time and service end time inconsistent issues

The summary is that when the front and back end to pass time, try to use UTC time.

How ISO dates and times are represented
if (! Date.prototype.toISOString) {  (function () {    function pad (number) {      if (number <) {        return ' 0 ' + number;      }      return number;    }    Date.prototype.toISOString = function () {      return this.getutcfullyear () +        '-' + pad (this.getutcmonth () + 1) +
    '-' + pad (this.getutcdate ()) +        ' T ' + pad (this.getutchours ()) +        ': ' + pad (this.getutcminutes ()) +        ': ' + pad (this.getutcseconds ()) +        '. ' + (This.getutcmilliseconds ()/+). ToFixed (3). Slice (2, 5) +        ' Z ';    } ;  } () );}

By Polyfill we can see how the ISO represents time, and the main feature is that the last one is "Z" and then the UTC time is always represented.

Additional supplements. ValueOf () and. GetTime ()

.valueOf()function and the .getTime() same.

This method is usually called inside JavaScript, not explicitly in code. What do you mean? No valueOf , then Date the instance is not able to perform the operation.

var obj = object.create (null); obj + 1; Uncaught Typeerror:cannot Convert object to primitive value (...)
. ToJSON

Looking directly at the name of this API, I thought it would return a JSON-formatted string, but it was actually something

New Date (). ToJSON ()//"2016-05-05t06:03:28.130z"

Actually, that's what happened.

Json.stringify (New Date ())//"" 2016-05-05t06:06:02.615z ""

Can the result be a parse?

Json.parse (Json.stringify (new Date ()))//"2016-05-05t06:19:24.766z" Json.parse (' "' + new Date (). ToJSON () + '" ')//"2016 -05-05t06:19:24.766z "

But the result is just a string. You need to give this string to the new Date() line.

. Tolocaleformat ()

Does not belong to any standard. is implemented in JavaScript 1.6. It seems that only Firefox self-sustaining this API, in fact, the correct posture is used.toLocaleDateString()

. Tolocale various string ()

.toLcale各种String(locales [, options]])

Mom, this API is a bit annoying, look at the MDN document you know. This API is used to localize the time.

Here's a little bit of my understanding of these parameters:

locales
 var date = new Date (DATE.UTC (3, 0, 0));//formats below assume the local time zone of the locale;//Ame Rica/los_angeles for the us//US 中文版 uses month-day-year orderalert (date.tolocalestring ("en"));//→ "12/19/2012, 7 : 00:00 PM "//British 中文版 uses Day-month-year orderalert (date.tolocalestring (" EN-GB "));//→" 20/12/2012 03:00:00 "// Korean uses Year-month-day Orderalert (date.tolocalestring ("Ko-kr"));//→ "2012. 12.20. ?? 12:00:00 "//Arabic in the most Arabic speaking countries uses real Arabic Digitsalert (date.tolocalestring (" Ar-eg "));//→"?? /?? /???? ?:??:?? ?" For Japanese, applications could want to use the Japanese calendar,//where is the year is the year of the Heisei Eraalert (d Ate.tolocalestring ("Ja-jp-u-ca-japanese"));//→ "24/12/20 12:00:00"//when requesting a language , such as//Balinese, include a fallback language, in this case Indonesianalert (date.tolocalestring (["Ban", "id"]);//→ " 20/12/2012 11.00.00 "

Output in the locales time zone and language of the indicated region.

options

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

  • localeMatcherChoosing what algorithm to match locally doesn't seem to be much use.
  • timeZoneSet the UTC time zone again
  • hour12Whether the 12-hour system
  • formatMatcherformatting of each date and time unit
    • weekdayPossible values are "narrow", "short", "long" .
    • eraPossible values are "narrow", "short", "long" .
    • yearPossible values are "numeric", "2-digit" .
    • monthPossible values are "numeric", "2-digit", "narrow", "short", "long" .
    • dayPossible values are "numeric", "2-digit" .
    • hourPossible values are "numeric", "2-digit" .
    • minutePossible values are "numeric", "2-digit" .
    • secondPossible values are "numeric", "2-digit" .
    • timeZoneNamePossible values are "short", "long" .

Chestnuts:

var date = new Date (DATE.UTC (3, 0, 0));d ate.tolocalestring ("en-us", {hour12:false}); "12/19/2012, 19:00:00" var options = {timezonename: ' Long ', weekday: "Long", Year: "2-digit", Month: "Narrow", Day: "Numer IC "};d ate.tolocalestring (" en-us ", options); "Thursday, D, C, China Standard Time"

Insert a JavaScript to display y-m-d h:i:s datetime format

Honest way.
Let date = new Date (); let result = [  [    date.getfullyear (),    date.getmonth () + 1,    date.getdate ()  ]. Join ('-'),  [    date.gethours (),    date.getminutes (),    date.getseconds ()  ].join (': ')].join ('). Replace (/\b\d\b/g, ' 0$& ');
Diao a little bit of a way
var date = new Date (), var result = date.tolocalestring (' Zh-cn ', {hour12:false}).  replace (/\//g, '-'). Replace (/\b\d \b/g, ' 0$& ');
Some useful time-libraries
    • Https://github.com/moment/moment
    • Https://github.com/rmm5t/jquery-timeago

The most detailed reading of JavaScript's Date

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.