簡體   English   中英

JavaScript-奇怪地使用Date.getDate()來獲取一個月的天數。 這是如何運作的?

[英]JavaScript - Weird usage of Date.getDate() for to get the days-count of a month. How does that work?

我已經在CodeReview上看到了代碼技術,技巧,黑客(您想如何稱呼它): https : //codereview.stackexchange.com/questions/142706/take-a-specified-weekday-and-check-if-它落在剩下的日子里

在第六行中,使用getDate()方法獲取一個月的天數。 將月份指定為上一個參數。

我已經嘗試過這些技術,並且似乎可行:

 var d = new Date(); var sep = new Date(d.getYear(), (d.getMonth() + 1), 0).getDate(); var oct = new Date(d.getYear(), (d.getMonth() + 2), 0).getDate(); var nov = new Date(d.getYear(), (d.getMonth() + 3), 0).getDate(); var dec = new Date(d.getYear(), (d.getMonth() + 4), 0).getDate(); var jan = new Date(d.getYear(), (d.getMonth() + 5), 0).getDate(); console.log(d.toLocaleString('en-US', { month: 'long' })); console.log('%s %s %s %s %s', sep, oct, nov, dec, jan); 

但是它怎么可能起作用呢?

我希望Date構造函數只接受有效的整數。

一個人可以給它一個喜歡的整數。 它不會引發異常。 但是:返回的值為廢料。

 var d = new Date(); var nov = new Date(d.getYear(), (d.getMonth() + 3), 31).getDate(); // November has 30 days. console.log('%s', nov); // => 31 var nov = new Date(d.getYear(), (d.getMonth() + 3), -21).getDate(); // November has 30 days. console.log('%s', nov); // 9 var nov = new Date(d.getYear(), (d.getMonth() + 3), 301).getDate(); // November has 30 days. console.log('%s', nov); // 27 

有見識的人可以解釋那里發生的事情嗎?

這只是Date類的一個屬性,如MDN所述:

如果將Date用作具有多個自變量的構造函數,則如果值大於其邏輯范圍(例如,將13作為月份值或將70作為分鍾值),則會調整相鄰的值。 例如,新的Date(2013,13,1)等同於新的Date(2014,1,1),兩者都為2014-02-01創建一個日期(請注意,該月是從0開始的)。 同樣,對於其他值:new Date(2013,2,1,0,70)等效於new Date(2013,2,1,1,10),兩者都為2013-03-01T01:10:00創建一個日期。

他們談論的值大於其邏輯范圍,但相同的邏輯適用於小於其邏輯范圍的值。

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

var d = new Date();

var nov = new Date(d.getYear(),(d.getMonth()+ 3),31).getDate(); // 11月有30天。 console.log('%s',11月); // => 31 Thu Dec 31 2016 2016 00:00:00 GMT + 0530(印度標准時間)

var nov = new Date(d.getYear(),(d.getMonth()+ 3),-21).getDate(); // 11月有30天。 console.log('%s',11月); // 9 Mon Nov 09 2016 00:00:00 GMT + 0530(India Standard Time)

var nov = new Date(d.getYear(),(d.getMonth()+ 3),301).getDate(); // 11月有30天。 console.log('%s',11月); // 27 Mon Sep 27 2017 00:00:00 GMT + 0530(India Standard Time)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM