[英]Calculate last day of month
如果您在Date.setFullYear
中提供0
作為dayValue
,您將獲得上個月的最后一天:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
在mozilla中提到了這種行為。 這是一個可靠的跨瀏覽器功能還是我應該看看其他方法?
var month = 0; // January var d = new Date(2008, month + 1, 0); console.log(d.toString()); // last day in January
IE 6: Thu Jan 31 00:00:00 CST 2008
IE 7: Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008
Opera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
輸出差異是由於toString()
實現的差異,而不是因為日期不同。
當然,僅僅因為上面確定的瀏覽器使用 0 作為上個月的最后一天並不意味着它們會繼續這樣做,或者沒有列出的瀏覽器會這樣做,但它增加了人們相信它應該可以工作的可信度。在每個瀏覽器中都以相同的方式。
我發現這對我來說是最好的解決方案。 讓 Date 對象為您計算它。
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
將 day 參數設置為 0 表示比該月的第一天少一天,即上個月的最后一天。
我會在下個月的第一天使用中間日期,並返回前一天的日期:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
用計算機術語來說, new Date()
和regular expression
解決方案很慢! 如果你想要一個超快速(和超神秘)的單行,試試這個(假設m
是Jan=1
格式)。 我不斷嘗試不同的代碼更改以獲得最佳性能。
我目前最快的版本:
在查看了這個相關的問題Leap year check using bitwise operators (驚人的速度)並發現了 25 & 15 幻數代表什么之后,我想出了這個優化的混合答案:
function getDaysInMonth(m, y) {
return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}
考慮到位移,這顯然假設您的m
和y
參數都是整數,因為將數字作為字符串傳遞會導致奇怪的結果。
JSFiddle:http: //jsfiddle.net/TrueBlueAussie/H89X3/22/
JSPerf 結果:http: //jsperf.com/days-in-month-head-to-head/5
由於某種原因, (m+(m>>3)&1)
1) 在幾乎所有瀏覽器上都比(5546>>m&1)
更有效。
唯一真正的速度競爭來自@GitaarLab,所以我創建了一個面對面的 JSPerf 供我們測試:http: //jsperf.com/days-in-month-head-to-head/5
它基於我的閏年答案在這里工作: javascript to findleap year this answer here 閏年檢查使用按位運算符(驚人的速度)以及以下二進制邏輯。
二進制月份的快速課程:
如果您以二進制形式解釋所需月份的索引(Jan = 1),您會注意到具有 31 天的月份要么清除了位 3 並設置了位 0,要么設置了位 3 並清除了位 0。
Jan = 1 = 0001 : 31 days
Feb = 2 = 0010
Mar = 3 = 0011 : 31 days
Apr = 4 = 0100
May = 5 = 0101 : 31 days
Jun = 6 = 0110
Jul = 7 = 0111 : 31 days
Aug = 8 = 1000 : 31 days
Sep = 9 = 1001
Oct = 10 = 1010 : 31 days
Nov = 11 = 1011
Dec = 12 = 1100 : 31 days
這意味着您可以使用>> 3
將值移位 3 位,使用原始^ m
對位進行異或運算,並使用& 1
查看位位置 0 中的結果是1
還是0
。 注意:事實證明+
比 XOR ( ^
) 稍快, (m >> 3) + m
在位 0 中給出相同的結果。
JSPerf 結果:http: //jsperf.com/days-in-month-perf-test/6
我的同事偶然發現了以下可能是更簡單的解決方案
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
對lebreeze提供的解決方案稍作修改:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
我最近不得不做類似的事情,這就是我想出的:
/**
* Returns a date set to the begining of the month
*
* @param {Date} myDate
* @returns {Date}
*/
function beginningOfMonth(myDate){
let date = new Date(myDate);
date.setDate(1)
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
return date;
}
/**
* Returns a date set to the end of the month
*
* @param {Date} myDate
* @returns {Date}
*/
function endOfMonth(myDate){
let date = new Date(myDate);
date.setDate(1); // Avoids edge cases on the 31st day of some months
date.setMonth(date.getMonth() +1);
date.setDate(0);
date.setHours(23);
date.setMinutes(59);
date.setSeconds(59);
return date;
}
將它傳入一個日期,它將返回一個設置為月初或月底的日期。
begninngOfMonth
函數是不言自明的,但是endOfMonth
函數中的內容是我將月份遞增到下個月,然后使用setDate(0)
將日期回滾到上個月的最后一天這是 setDate 規范的一部分:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp
然后,我將小時/分鍾/秒設置為一天結束,這樣,如果您使用某種 API 預期日期范圍,您將能夠捕獲最后一天的全部內容。 這部分可能超出了原始帖子的要求,但它可以幫助其他人尋找類似的解決方案。
編輯:如果您想更加精確,您也可以加倍努力並使用setMilliseconds()
設置毫秒。
試試這個。
lastDateofTheMonth = new Date(year, month, 0)
例子:
new Date(2012, 8, 0)
輸出:
Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
這對我有用。 將提供給定年份和月份的最后一天:
var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);
請注意本月最后一個看起來像這樣的任何答案:
var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)
這適用於大多數日期,但如果date
已經是該月的最后一天,並且該月的天數比下個月的天數多,則會失敗。
例子:
假設date
是07/31/21
。
然后last.setMonth(last.getMonth() + 1)
增加月份,但將日期設置為31
。
你得到一個08/31/21
的 Date 對象,
這實際上是09/01/21
。
那么last.setDate(0)
結果是08/31/21
而我們真正想要的是07/31/21
。
這個很好用:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
這將為您提供當前月份的第一天和最后一天。
如果您需要更改“年份”,請刪除 d.getFullYear() 並設置您的年份。
如果您需要更改“月份”,請刪除 d.getMonth() 並設置您的年份。
var d = new Date(); var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var fistDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth(), 1).getDay())]; var LastDayOfMonth = days[(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDay())]; console.log("First Day :" + fistDayOfMonth); console.log("Last Day:" + LastDayOfMonth); alert("First Day :" + fistDayOfMonth); alert("Last Day:" + LastDayOfMonth);
嘗試這個:
function _getEndOfMonth(time_stamp) {
let time = new Date(time_stamp * 1000);
let month = time.getMonth() + 1;
let year = time.getFullYear();
let day = time.getDate();
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
case 2:
if (_leapyear(year))
day = 29;
else
day = 28;
break
}
let m = moment(`${year}-${month}-${day}`, 'YYYY-MM-DD')
return m.unix() + constants.DAY - 1;
}
function _leapyear(year) {
return (year % 100 === 0) ? (year % 400 === 0) : (year % 4 === 0);
}
您可以通過以下代碼獲取當月的第一個和最后一個日期:
var dateNow = new Date();
var firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1);
var lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);
或者如果您想以自定義格式格式化日期,那么您可以使用 moment js
var dateNow= new Date();
var firstDate=moment(new Date(dateNow.getFullYear(),dateNow.getMonth(), 1)).format("DD-MM-YYYY");
var currentDate = moment(new Date()).format("DD-MM-YYYY"); //to get the current date var lastDate = moment(new
Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0)).format("DD-MM-YYYY"); //month last date
下面的函數給出了該月的最后一天:
function getLstDayOfMonFnc(date) { return new Date(date.getFullYear(), date.getMonth(), 0).getDate() } console.log(getLstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 29 console.log(getLstDayOfMonFnc(new Date(2017, 2, 15))) // Output : 28 console.log(getLstDayOfMonFnc(new Date(2017, 11, 15))) // Output : 30 console.log(getLstDayOfMonFnc(new Date(2017, 12, 15))) // Output : 31
同樣,我們可以得到該月的第一天:
function getFstDayOfMonFnc(date) { return new Date(date.getFullYear(), date.getMonth(), 1).getDate() } console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1
這是一個保存 GMT 和初始日期時間的答案
var date = new Date(); var first_date = new Date(date); //Make a copy of the date we want the first and last days from first_date.setUTCDate(1); //Set the day as the first of the month var last_date = new Date(first_date); //Make a copy of the calculated first day last_date.setUTCMonth(last_date.getUTCMonth() + 1); //Add a month last_date.setUTCDate(0); //Set the date to 0, this goes to the last day of the previous month console.log(first_date.toJSON().substring(0, 10), last_date.toJSON().substring(0, 10)); //Log the dates with the format yyyy-mm-dd
const today = new Date();
let beginDate = new Date();
let endDate = new Date();
// fist date of montg
beginDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 1}-01 00:00:00`
);
// end date of month
// set next Month first Date
endDate = new Date(
`${today.getFullYear()}-${today.getMonth() + 2}-01 :23:59:59`
);
// deducting 1 day
endDate.setDate(0);
function getLastDay(y, m) {
return 30 + (m <= 7 ? ((m % 2) ? 1 : 0) : (!(m % 2) ? 1 : 0)) - (m == 2) - (m == 2 && y % 4 != 0 || !(y % 100 == 0 && y % 400 == 0));
}
設置您需要約會的月份,然后將日期設置為零,因此月份在日期函數中從 1 - 31 開始,然后獲取最后一天^^
var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate(); console.log(last);
我知道這只是語義問題,但我最終以這種形式使用它。
var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);
由於函數是從內部參數向外解析的,因此它的工作原理相同。
然后,您可以用所需的詳細信息替換年和月/年,無論它是從當前日期開始的。 或特定的月份/年份。
如果您需要以毫秒為單位的確切月底(例如時間戳):
d = new Date() console.log(d.toString()) d.setDate(1) d.setHours(23, 59, 59, 999) d.setMonth(d.getMonth() + 1) d.setDate(d.getDate() - 1) console.log(d.toString())
接受的答案對我不起作用,我做了如下。
$( function() { $( "#datepicker" ).datepicker(); $('#getLastDateOfMon').on('click', function(){ var date = $('#datepicker').val(); // Format 'mm/dd/yy' eg: 12/31/2018 var parts = date.split("/"); var lastDateOfMonth = new Date(); lastDateOfMonth.setFullYear(parts[2]); lastDateOfMonth.setMonth(parts[0]); lastDateOfMonth.setDate(0); alert(lastDateOfMonth.toLocaleDateString()); }); });
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <p>Date: <input type="text" id="datepicker"></p> <button id="getLastDateOfMon">Get Last Date of Month </button> </body> </html>
這將為您提供當前月份的最后一天。
注意:在 ios 設備上包括時間。 #gshoanganh
var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
如果您只需要為我計算出一個月的最后一個日期。
var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();
const lastDay = new Date(year, month +1, 0).getDate();
console.log(lastDay);
在這里試試https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php
就我而言,這段代碼很有用
end_date = new Date(2018, 3, 1).toISOString().split('T')[0] console.log(end_date)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.