Date leap year validation - javascript

function checkDate(date)
{
//how to use this function since many people recommend this one
isLeap = new Date(date, 1, 29).getMonth() == 1;
return isLeap;
}
In html script, i wrote it as but i can't validate my Date of Order. I need to use javascript and it should be able to validate it including leap year. The function I used above can't work. Any helps will be appreciated.

To check if it's leap year :
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
to check if the extra day is valid -- is to check how many days were in that month (and if they equal to dd):
32 - new Date(2000, 1, 32).getDate() //1 here is FEB
do if some says : 29 feb 2000
so
32 - new Date(2000, 1, 32).getDate()//29
which is fine . cuz 29==29.
BUT
do if some says : 29 feb 2001
32 - new Date(2001, 1, 32).getDate()//28
and 28!=29 so it's not valid date.

Related

End of Month using javascript [duplicate]

If you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
There is reference to this behaviour at mozilla. Is this a reliable cross-browser feature or should I look at alternative methods?
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)
Output differences are due to differences in the toString() implementation, not because the dates are different.
Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.
I find this to be the best solution for me. Let the Date object calculate it for you.
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.
I would use an intermediate date with the first day of the next month, and return the date from the previous day:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
In computer terms, new Date() and regular expression solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format). I keep trying different code changes to get the best performance.
My current fastest version:
After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers (note the parameters m & y must obviously be integers for this to work):
function getDaysInMonth(m, y) {
return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}
Given the bit-shifting this obviously assumes that your m & y parameters are both integers, as passing numbers as strings would result in weird results.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/
JSPerf results: http://jsperf.com/days-in-month-head-to-head/5
For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.
The only real competition for speed is from #GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5
It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.
A quick lesson in binary months:
If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.
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
That means you can shift the value 3 places with >> 3, XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1. Note: It turns out + is slightly faster than XOR (^) and (m >> 3) + m gives the same result in bit 0.
JSPerf results: http://jsperf.com/days-in-month-perf-test/6
My colleague stumbled upon the following which may be an easier solution
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
stolen from http://snippets.dzone.com/posts/show/2099
A slight modification to solution provided by lebreeze:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
I recently had to do something similar, this is what I came up with:
/**
* 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;
}
Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.
The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
https://www.w3schools.com/jsref/jsref_setdate.asp
I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.
Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.
How NOT to do it
Beware of any answers for the last of the month that look like this:
var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)
This works for most dates, but fails if date is already the last day of the month, on a month that has more days than the following month.
Example:
Suppose date is 07/31/21.
Then last.setMonth(last.getMonth() + 1) increments the month, but keeps the day set at 31.
You get a Date object for 08/31/21,
which is actually 09/01/21.
So then last.setDate(0) results in 08/31/21 when what we really wanted was 07/31/21.
try this one.
lastDateofTheMonth = new Date(year, month, 0)
example:
new Date(2012, 8, 0)
output:
Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
This works for me.
Will provide last day of given year and month:
var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);
This one works nicely:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
You can get the First and Last Date in the current month by following the code:
var dateNow = new Date();
var firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1);
var lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);
or if you want to format the date in your custom format then you can use 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
This will give you current month first and last day.
If you need to change 'year' remove d.getFullYear() and set your year.
If you need to change 'month' remove d.getMonth() and set your year.
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);
Try this:
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);
}
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);
Below function gives the last day of the month :
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
Similarly we can get first day of the month :
function getFstDayOfMonFnc(date) {
return new Date(date.getFullYear(), date.getMonth(), 1).getDate()
}
console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1
Here is an answer that conserves GMT and time of the initial date
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
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));
}
set month you need to date and then set the day to zero ,so month begin in 1 - 31 in date function then get the last day^^
var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate();
console.log(last);
I know it's just a matter of semantics, but I ended up using it in this form.
var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);
Since functions are resolved from the inside argument, outward, it works the same.
You can then just replace the year, and month / year with the required details, whether it be from the current date. Or a particular month / year.
If you need exact end of the month in miliseconds (for example in a timestamp):
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())
The accepted answer doesn't work for me, I did it as below.
$( 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>
This will give you last day of current month.
notes: on ios device include time.
#gshoanganh
var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
if you just need to get the last date of a month following worked out for me.
var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();
const lastDay = new Date(year, month +1, 0).getDate();
console.log(lastDay);
try it out here https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php
In my case, this code was useful
end_date = new Date(2018, 3, 1).toISOString().split('T')[0]
console.log(end_date)

Counting weekday cycles in JavaScript

My school runs on a 7 day cycle, so if today (2016/02/26) was day 1, tomorrow would be day 0, Monday would be day 2, and the next day 1 would be 2016/03/08. I know it's very strange, but I'm trying to find a way to use the Date object in JavaScript and add on one cycle, that is 7 days, not including weekends.
I would like to emphasize that weekends DO NOT COUNT towards day counting. I'm trying to find a way to omit weekends and easily find the next day 1 or day 5 or whatever.
There are either 1 or 2 weekends in your 7-day school cycle, depending on the start day of the cycle, so the actual cycle length is either 9 or 11 days. The Date.getDay() method gives you access to the day of the week, so a possible solutions might look like this:
var myDate= new Date();
switch(true) {
//Sunday=0, Saturday=6
case(myDate.getDay() % 6 == 0) : alert('weekend!'); return;
case (myDate.getDay() < 4) : // Mon, Tues, Wed
myDate.setDate(myDate.getDate() + 9);
break;
case (myDate.getDay() < 6) : // Thu, Fri
myDate.setDate(myDate.getDate() + 11);
break;
}

populate dates in dropdown using javascript [duplicate]

I've been using this function but I'd like to know what's the most efficient and accurate way to get it.
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
function daysInMonth (month, year) { // Use 1 for January, 2 for February, etc.
return new Date(year, month, 0).getDate();
}
console.log(daysInMonth(2, 1999)); // February in a non-leap year.
console.log(daysInMonth(2, 2000)); // February in a leap year.
Day 0 is the last day in the previous month. Because the month constructor is 0-based, this works nicely. A bit of a hack, but that's basically what you're doing by subtracting 32.
See more :
Number of days in the current month
Some answers (also on other questions) had leap-year problems or used the Date-object. Although javascript's Date object covers approximately 285616 years (100,000,000 days) on either side of January 1 1970, I was fed up with all kinds of unexpected date inconsistencies across different browsers (most notably year 0 to 99). I was also curious how to calculate it.
So I wrote a simple and above all, small algorithm to calculate the correct (Proleptic Gregorian / Astronomical / ISO 8601:2004 (clause 4.3.2.1), so year 0 exists and is a leap year and negative years are supported) number of day's for a given month and year.
It uses the short-circuit bitmask-modulo leapYear algorithm (slightly modified for js) and common mod-8 month algorithm.
Note that in AD/BC notation, year 0 AD/BC does not exist: instead year 1 BC is the leap-year!
IF you need to account for BC notation then simply subtract one year of the (otherwise positive) year-value first!! (Or subtract the year from 1 for further year-calculations.)
function daysInMonth(m, y){
return m===2?y&3||!(y%25)&&y&15?28:29:30+(m+(m>>3)&1);
}
<!-- example for the snippet -->
<input type="text" value="enter year" onblur="
for( var r='', i=0, y=+this.value
; 12>i++
; r+= 'Month: ' + i + ' has ' + daysInMonth(i, y) + ' days<br>'
);
this.nextSibling.innerHTML=r;
" /><div></div>
Note, months must be 1-based!
Note, this is a different algorithm then the magic number lookup I used in my Javascript calculate the day of the year (1 - 366) answer, because here the extra branch for the leap-year is only needed for February.
If you call this function often, it may be useful to cache the value for better performance.
Here is caching version of FlySwat's answer:
var daysInMonth = (function() {
var cache = {};
return function(month, year) {
var entry = year + '-' + month;
if (cache[entry]) return cache[entry];
return cache[entry] = new Date(year, month, 0).getDate();
}
})();
With moment.js you can use daysInMonth() method:
moment().daysInMonth(); // number of days in the current month
moment("2012-02", "YYYY-MM").daysInMonth() // 29
moment("2012-01", "YYYY-MM").daysInMonth() // 31
To take away confusion I would probably make the month string based as it is currently 0 based.
function daysInMonth(month,year) {
var monthNum = new Date(Date.parse(month +" 1,"+year)).getMonth()+1
return new Date(year, monthNum, 0).getDate();
}
daysInMonth('feb', 2015)
//28
daysInMonth('feb', 2008)
//29
One-liner direct computation (no Date object):
//m is 0-based, Jan = 0, Dec = 11
function daysInMonth(m,y){
return 31-(m-1?m%7&1:y&(y%25?3:15)?3:2);
}
console.log(daysInMonth(1, 2003), "days in February in the non-leap year 2003");
console.log(daysInMonth(1, 2004), "days in February in the leap year 2004");
console.log(daysInMonth(1, 2100), "days in February in the non-leap year 2100");
console.log(daysInMonth(1, 2000), "days in February in the leap year 2000");
console.log(daysInMonth(0, 2022), "days in January 2022");
console.log(daysInMonth(1, 2022), "days in February 2022");
console.log(daysInMonth(2, 2022), "days in March 2022");
console.log(daysInMonth(3, 2022), "days in April 2022");
console.log(daysInMonth(4, 2022), "days in May 2022");
console.log(daysInMonth(5, 2022), "days in June 2022");
console.log(daysInMonth(6, 2022), "days in July 2022");
console.log(daysInMonth(7, 2022), "days in August 2022");
console.log(daysInMonth(8, 2022), "days in September 2022");
console.log(daysInMonth(9, 2022), "days in October 2022");
console.log(daysInMonth(10, 2022), "days in November 2022");
console.log(daysInMonth(11, 2022), "days in December 2022");
Explanation
The main idea is to assume that months have 31 days, but subtract 1 if the month is April, June, September, or November; subtract 2 if the month is February in a leap year; or subtract 3 if the month is February in a non-leap year.
In the ternary expression (m - 1 ? /* Not February */ : /* February */), the expression m - 1 checks whether the month is February.
For other months than February, the expression m % 7 makes m even for months with 31 days, and odd for the rest. Subtracting the lowest bit (& 1) results in 31 − 1 days for April, June, September, and November, and 31 − 0 days for the rest.
For February, the expression y & (y % 25 ? 3 : 15) is falsy for leap years, resulting in 31 − 2 days in February. Otherwise, February is 31 − 3 days.
Here is goes
new Date(2019,2,0).getDate(); //28
new Date(2020,2,0).getDate(); //29
May be bit over kill when compared to selected answer :) But here it is:
function getDayCountOfMonth(year, month) {
if (month === 3 || month === 5 || month === 8 || month === 10) {
return 30;
}
if (month === 1) {
if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
return 29;
} else {
return 28;
}
}
return 31;
};
console.log(getDayCountOfMonth(2020, 1));
I found the above code over here: https://github.com/ElemeFE/element/blob/dev/src/utils/date-util.js
function isLeapYear(year) {
return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
};
const getDaysInMonth = function (year, month) {
return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};
console.log(getDaysInMonth(2020, 1));
I found the above code over here: https://github.com/datejs/Datejs/blob/master/src/core.js
ES6 syntax
const d = (y, m) => new Date(y, m, 0).getDate();
returns
console.log( d(2020, 2) );
// 29
console.log( d(2020, 6) );
// 30
function numberOfDays(iMonth, iYear) {
var myDate = new Date(iYear, iMonth + 1, 1); //find the fist day of next month
var newDate = new Date(myDate - 1); //find the last day
return newDate.getDate(); //return # of days in this month
}
Considering leap years:
function (year, month) {
var isLeapYear = ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
return [31, (isLeapYear ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
}
If you want the number of days in the current month of a Date object, consider the following method:
Date.prototype.getNumberOfDaysInMonth = function(monthOffset) {
if (monthOffset !== undefined) {
return new Date(this.getFullYear(), this.getMonth()+monthOffset, 0).getDate();
} else {
return new Date(this.getFullYear(), this.getMonth(), 0).getDate();
}
}
Then you can run it like this:
var myDate = new Date();
myDate.getNumberOfDaysInMonth(); // Returns 28, 29, 30, 31, etc. as necessary
myDate.getNumberOfDaysInMonth(); // BONUS: This also tells you the number of days in past/future months!
In a single line:
// month is 1-12
function getDaysInMonth(year, month){
return month == 2 ? 28 + (year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? 1 : 0) : 1):0) : 31 - (month - 1) % 7 % 2;
}
Perhaps not the most elegant solution, but easy to understand and maintain; and, it's battle-tested.
function daysInMonth(month, year) {
var days;
switch (month) {
case 1: // Feb, our problem child
var leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
days = leapYear ? 29 : 28;
break;
case 3: case 5: case 8: case 10:
days = 30;
break;
default:
days = 31;
}
return days;
},
If you are going to pass a date variable this may helpful
const getDaysInMonth = date =>
new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
daysInThisMonth = getDaysInMonth(new Date());
console.log(daysInThisMonth);
One-liner, without using Date objects:
const countDays = (month, year) => 30 + (month === 2 ? (year % 4 === 0 && 1) - 2 : (month + Number(month > 7)) % 2);
returns:
countDays(11,2020) // 30
countDays(2,2020) // 29
countDays(2,2021) // 28
To get the number of days in the current month
var nbOfDaysInCurrentMonth = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 0)).getDate()
console.log(nbOfDaysInCurrentMonth)
You can get days in month by this command:
new Date(year, month, 0).getDate();
Try this - it returns dictionary with month: days mapping, I think it will be very useful in most cases when people enter this topic:
const getMonthsDaysForYear = (year) => {
let monthDaysDictionary = {};
for(let i = 1; i <= 11; i++) {
const date = new Date(year, i + 1, 0);
const monthName = date.toLocaleString('en-GB', { month: 'long' });
monthDaysDictionary[monthName] = date.getDate();
}
return monthDaysDictionary;
}
getMonthsDaysForYear(2022);
Note: that month should be started with 1 as it is mentioned in this answer.
See my function and a test of it:
function numberOfDays(year, month)
{
// Reference:
// https://arslankuyumculuk.com/how-to-calculate-leap-year-formula/ (2022-05-20 16:45 UTC)
numDays=0;
switch(month)
{
case 1:
numDays=31;
break;
case 2:
numDays=28;
break;
case 3:
numDays=31;
break;
case 4:
numDays=30;
break;
case 5:
numDays=31;
break;
case 6:
numDays=30;
break;
case 7:
numDays=31;
break;
case 8:
numDays=31;
break;
case 9:
numDays=30;
break;
case 10:
numDays=31;
break;
case 11:
numDays=30;
break;
case 12:
numDays=31;
break;
}
if(month==2)
{
if( (year % 100) == 0 )
{
if( (year % 400) == 0 )
{
numDays=29;
}
}
else
{
if( (year % 4) == 0 )
{
numDays=29;
}
}
}
//
return numDays;
}
// Test:
const years = [2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2100,2400];
month=2;
for (let i = 0; i < years.length; i++)
{
let text = "";
text += years[i] + '/' + month.toString() + ": " + numberOfDays(years[i], month).toString();
alert(text);
}
for (let m = 1; m <= 12; m++)
{
let text2 = "";
text2 += "2022/" + m.toString() + ": " + numberOfDays(2022, m).toString();
alert(text2);
}
#Tomas Langkaas : I've implemented essentially the same function you've mentioned above in awk, with some minor improvements :
using conventional arithmetic instead of bit-wise AND ( & ), plus not using implementation-dependent features, making it fully POSIX-awk-complaint and portable (tested and confirmed working on mawk, gawk, and nawk)
2. user can now directly input actual month numbers of 1 - 12 instead of having to remember to pre-adjust them to 0 - 11
instead of relying on hard-coded numerics, every constant, offset, modulo base etc now dynamically generated on the fly by the function itself ,
while simultaneously being extremely temp variables efficient by recycling both the input month and year variables the moment their original values are no longer required, thus
when February is being called without a year-value, it defaults to NOT-being a leap year, regardless of what the present year is
{m,g,n}awk '
function _____(_,__) {
#
# _| Month mm: [1-12]
# __| Year yyyy:
# |---> #-days:
# in yyyy:mm: combo
return -(\
_^(_<_) != --_ \
? (_ %((_+=_+=_^=_<_) +--_)) %--_\
: (_+=_^=_<_) + (__ == "" ||
__ % (_+=_) ||
__% (_*(_*=_++)+_) == ! (__ % (_*_))\
) ) \
-(_^=_<_) -+- ++_^_^_*_
}'
2 1600 29
2 1700 28
2 1800 28
2 1868 29
2 1900 28
2 1912 29
2 1956 29
2 2000 29
2 2012 29
2 2016 29
2 2018 28
2 2020 29
2 2022 28
2 2024 29

Change day in a function used by onclick, javascript

Hey there i have the following problem. I am sure you could help me:
I have a button that change the hour +1 hour or - 1 hour. But the date jumps from 00UTC to 23 UTC on the same day and not the day before.
Note: addZero completes the string from 1 to "01" (it is because an image string needs 01 02 03 )
function switch_image(i) {
if (i == 0) {
d.setUTCHours(d.getUTCHours() - 1);
if (d.getUTCHours() == 23) {
d.setUTCDate(d.getUTCDate() - 1);
}
h = addZero(d.getUTCHours());
} else {
d.setUTCHours(d.getUTCHours() + 1);
if (d.getUTCHours() == 0) {
d.setUTCDate(d.getUTCDate() + 1);
}
h = addZero(d.getUTCHours());
}
}
Thanks a lot for your help ;)
I found the solution by myself. I forgot to set the variable for days (it s t, for hpurs its h) new. Best regards .
See the following function which adds a constant value to another date using Date.UTC(1970,0,1) as a starting value (Jan 1, 1970 is the Unix epoch). Note that months and years aren't included because they aren't constant times (there are leap years and months don't span the same number of days).
Date.prototype.addTime = function(days,hours,minutes,seconds,milliseconds){
for(var i=0;i<arguments.length;i++){
arguments[i]=parseInt(arguments[i]);
}
return new Date(this.getTime() +
Date.UTC(1970, 0,
(isNaN(days) ? 0 : days) + 1,
isNaN(hours) ? 0 : hours,
isNaN(minutes) ? 0 : minutes,
isNaN(seconds) ? 0 : seconds,
isNaN(milliseconds) ? 0 : milliseconds));
}
document.body.innerHTML = new Date(Date.now()).addTime(1,1).toString(); //Adds 1 day,1 hour
Reference: MDN

Calculate last day of month

If you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:
d = new Date(); d.setFullYear(2008, 11, 0); // Sun Nov 30 2008
There is reference to this behaviour at mozilla. Is this a reliable cross-browser feature or should I look at alternative methods?
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)
Output differences are due to differences in the toString() implementation, not because the dates are different.
Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.
I find this to be the best solution for me. Let the Date object calculate it for you.
var today = new Date();
var lastDayOfMonth = new Date(today.getFullYear(), today.getMonth()+1, 0);
Setting day parameter to 0 means one day less than first day of the month which is last day of the previous month.
I would use an intermediate date with the first day of the next month, and return the date from the previous day:
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
In computer terms, new Date() and regular expression solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format). I keep trying different code changes to get the best performance.
My current fastest version:
After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers (note the parameters m & y must obviously be integers for this to work):
function getDaysInMonth(m, y) {
return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
}
Given the bit-shifting this obviously assumes that your m & y parameters are both integers, as passing numbers as strings would result in weird results.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/
JSPerf results: http://jsperf.com/days-in-month-head-to-head/5
For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.
The only real competition for speed is from #GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5
It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.
A quick lesson in binary months:
If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.
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
That means you can shift the value 3 places with >> 3, XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1. Note: It turns out + is slightly faster than XOR (^) and (m >> 3) + m gives the same result in bit 0.
JSPerf results: http://jsperf.com/days-in-month-perf-test/6
My colleague stumbled upon the following which may be an easier solution
function daysInMonth(iMonth, iYear)
{
return 32 - new Date(iYear, iMonth, 32).getDate();
}
stolen from http://snippets.dzone.com/posts/show/2099
A slight modification to solution provided by lebreeze:
function daysInMonth(iMonth, iYear)
{
return new Date(iYear, iMonth, 0).getDate();
}
I recently had to do something similar, this is what I came up with:
/**
* 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;
}
Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.
The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate
https://www.w3schools.com/jsref/jsref_setdate.asp
I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.
Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.
How NOT to do it
Beware of any answers for the last of the month that look like this:
var last = new Date(date)
last.setMonth(last.getMonth() + 1) // This is the wrong way to do it.
last.setDate(0)
This works for most dates, but fails if date is already the last day of the month, on a month that has more days than the following month.
Example:
Suppose date is 07/31/21.
Then last.setMonth(last.getMonth() + 1) increments the month, but keeps the day set at 31.
You get a Date object for 08/31/21,
which is actually 09/01/21.
So then last.setDate(0) results in 08/31/21 when what we really wanted was 07/31/21.
try this one.
lastDateofTheMonth = new Date(year, month, 0)
example:
new Date(2012, 8, 0)
output:
Date {Fri Aug 31 2012 00:00:00 GMT+0900 (Tokyo Standard Time)}
This works for me.
Will provide last day of given year and month:
var d = new Date(2012,02,0);
var n = d.getDate();
alert(n);
This one works nicely:
Date.prototype.setToLastDateInMonth = function () {
this.setDate(1);
this.setMonth(this.getMonth() + 1);
this.setDate(this.getDate() - 1);
return this;
}
You can get the First and Last Date in the current month by following the code:
var dateNow = new Date();
var firstDate = new Date(dateNow.getFullYear(), dateNow.getMonth(), 1);
var lastDate = new Date(dateNow.getFullYear(), dateNow.getMonth() + 1, 0);
or if you want to format the date in your custom format then you can use 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
This will give you current month first and last day.
If you need to change 'year' remove d.getFullYear() and set your year.
If you need to change 'month' remove d.getMonth() and set your year.
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);
Try this:
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);
}
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);
Below function gives the last day of the month :
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
Similarly we can get first day of the month :
function getFstDayOfMonFnc(date) {
return new Date(date.getFullYear(), date.getMonth(), 1).getDate()
}
console.log(getFstDayOfMonFnc(new Date(2016, 2, 15))) // Output : 1
Here is an answer that conserves GMT and time of the initial date
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
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));
}
set month you need to date and then set the day to zero ,so month begin in 1 - 31 in date function then get the last day^^
var last = new Date(new Date(new Date().setMonth(7)).setDate(0)).getDate();
console.log(last);
I know it's just a matter of semantics, but I ended up using it in this form.
var lastDay = new Date(new Date(2008, 11+1,1) - 1).getDate();
console.log(lastDay);
Since functions are resolved from the inside argument, outward, it works the same.
You can then just replace the year, and month / year with the required details, whether it be from the current date. Or a particular month / year.
If you need exact end of the month in miliseconds (for example in a timestamp):
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())
The accepted answer doesn't work for me, I did it as below.
$( 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>
This will give you last day of current month.
notes: on ios device include time.
#gshoanganh
var date = new Date();
console.log(new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59));
if you just need to get the last date of a month following worked out for me.
var d = new Date();
const year = d.getFullYear();
const month = d.getMonth();
const lastDay = new Date(year, month +1, 0).getDate();
console.log(lastDay);
try it out here https://www.w3resource.com/javascript-exercises/javascript-date-exercise-9.php
In my case, this code was useful
end_date = new Date(2018, 3, 1).toISOString().split('T')[0]
console.log(end_date)

Categories

Resources