I would be grateful for your help. How to set the range from 15 December to 15 January?
$(document).ready(function() {
var month = (new Date()).getMonth();
if (month < 2 || month === 11) {
$("#block").css("background-color", "#1D30C4");
}
else {
$("#block").css("background-color", "#C41D2C");
}
});
var block=$('#block');
var cd= new Date();
var startDate= new Date(cd.getFullYear(),11,15,0,0,0,0);
var endDate= new Date(cd.getFullYear()+1,0,15,0,0,0,0);
if(cd.getTime()>=startDate.getTime() && cd.getTime()<=endDate.getTime()){
$("#block").css("background-color", "#1D30C4");
}else{
$("#block").css("background-color", "#C41D2C");
}
please note that month in javascript starts with 0
here is jsbin link
https://jsbin.com/tafijucono/edit?html,css,js,output
Try the following:
var d = new Date();
var day = d.getDate();
var month = d.getMonth();
if((month > 11 && day > 14) || (month < 2 && day < 16)){ ...
Dates can be compared as if they are integers (since they contain a time value that is an integer representing an instant in time). So if you want to see if a date is between two other dates, then you can create two date objects and see if others lie between them:
// See if currently between 15 December 2015 and 15 January 2016 inclusive
// Start at 15-Dec-2015 00:00:00
var startDate = new Date(2015,11,15);
// End at 16-Jan-2015 00:00:00 so includes 15 Jan but not 16 Jan
var endDate = new Date(2016,0,16);
var now = new Date();
if (now > startDate && now < endDate) {
document.write("In range");
} else {
document.write("Out of range");
}
Related
I found an earlier question regarding pulling up dates that are marked as future here (Date should not be older than 1 year from current date (Today's date) in javascript)
This works great and is a great piece of work. The issue I'm having is the software we use tries to force everything to use USA date format and we're based in UK. This is fine, I can change the code to mark down as the correct date format for todays date (and it recognises it as UK! ... and I change the input date and it recognises it as GMT!. Great, that means it works right?)
No such luck. Whenever I select for example 06/05/2020 it marks it as 5th June. Even though it looks like all the dates are being marked to grab the UK date based on the input. (keep in mind, it's doing that for todays date). I think my confusion is coming because the console.log error is this
"This is enDateFri Jun 05 2020 00:00:00 GMT+0100 (British Summer Time)" When inputting 06/05/2020. It recognises it as GMT but not as the UK date? I did use the setlocale function to see if it made any difference but no such luck.
function validateNetworthDate() {
var dateValue = $(".eyeTest input").val();
var currentTime = new Date();
var currentDay = currentTime.getDate();
var currentMonth = currentTime.getMonth() + 1; //As January is 0!
var currentYear = currentTime.getFullYear();
if (currentDay < 10) {
currentDay = '0' + currentDay
}
if (currentMonth < 10) {
currentMonth = '0' + currentMonth
}
var enteredDay = dateValue.substr(0, 2);
var enteredMonth = dateValue.substr(3, 2);
var enteredYear = dateValue.substr(6, 4);
var enteredDateFormat = enteredDay + '/' + enteredMonth + '/' + enteredYear;
console.log(enteredDateFormat)
// var enteredDateFormat=dateValue;
//console.log("This is entered date format " + enteredDateFormat);
var enDate = new Date(enteredDateFormat);
var yearAgoTime = new Date().setFullYear(currentTime.getFullYear() - 2);
//console.log(yearAgoTime)
var compDate = currentTime - enDate;
console.log("This is enDate " + enDate)
if (compDate < 0) {
console.log("future date not allowed");
alert("future date not allowed");
$('.eyeTest input').addClass('numNeg');
}
else {
$('.eyeTest input').removeClass('numNeg');
$('.eyeTest input').addClass('numPos');
}
var compDate2 = enDate - yearAgoTime;
if (compDate2 < 0) {
console.log("More than 2 year ago not allowed.");
alert("Eye Test must be no more than 2 years ago");
$('.eyeTest input').addClass('numNeg');
}
else {
$('.eyeTest input').removeClass('numNeg');
$('.eyeTest input').addClass('numPos');
}
}
I'm supposed to write a code for codewars to find out the number of times a month ends with a Friday within a range of years.
To start off, I did research and found out several solutions but I still couldn't figure out the results in the console.log.
The first solution is from this tutorial:
In this code, the solution is
let LastDay = new Date(1998, 5 + 1, 0).getDate();
I was able to get the date, but it wasn't clear which day the date falls upon.
Then I found another solution at w3schools. This solution also set the date to be the last day of this month:
var d = new Date();
d.setMonth(d.getMonth() +1, 0);
document.getElementById("demo").innerHTML = d;
However, it works if it displays it as innerHTML = Sat Nov 30 2019 00:57:09 GMT-0500 (Eastern Standard Time). However, when I tried to rewrite the code and console.log it like in this example:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(lastday);
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting. I thought that if it does display the dates, starting with the day, I can convert the date to string or array and check if the first element is Friday and then add it to the counter in the code I'm writing. How do I get the code to display the way I want it to.
something like this will work...
function LastDayOfMonth(Year, Month) {
return new Date((new Date(Year, Month, 1)) - 1);
}
var d = LastDayOfMonth(new Date().getYear(), new Date().getMonth())
//var d = LastDayOfMonth(2009, 11)
var dayName = d.toString().split(' ')[0];
console.log(dayName)
The result I got was 1575093343211. I don't understand how it displays those numbers instead of the dates I was expecting
Because you console.log the output of the setMonth method, not the date object:
let lastday = d.setMonth(month, 0);
console.log(lastday);
According to the documentation, the setMonth method returns:
The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date.
Instead you should use that output to create a new instance of the date object:
let lastday = new Date(d.setMonth(month, 0));
console.log(lastday);
Algorithms to get the last day of the month are generally based on setting a date to day 0 of the following month, which ends up being the last day of the required month.
E.g. to get the last day for June, 2019 (noting that 6 is July, not June):
let endOfJune = new Date(2019, 6, 0):
Once you have the date, you can get the day where 0 is Sunday, 1 is Monday, etc. and 5 is Friday:
let endOfJuneDay = endOfJune.getDay();
The set* methods modify the Date they're called on and return the time value for the modified date. So you don't need to assign the result to anything:
let d = new Date();
let month = d.getMonth() + 1;
// Set date to the new month
d.setMonth(month, 0);
console.log(d);
So if you want to loop over the months for a range of years and get the number that end with a Friday (or any particular day), you might loop over the months something like:
/*
** #param {number} startYear - start year of range
** #param {number} endYear - end year of range
** #param {number} dat - day number, 0 = Sunday, 1 = Monday, etc.
** default is 0 (Sunday)
*/
function countEOMDay(startYear, endYear, day = 0) {
// startYear must be <= end year
if (startYear > endYear) return;
// Start on 31 Jan of start year
let start = new Date(startYear, 0, 31);
// End on 31 Dec of end year
let end = new Date(endYear, 11, 31);
let count = 0;
// Loop over months from start to end
while (start <= end) {
// Count matching days
if (start.getDay() == day) {
++count;
}
// Increment month to end of next month
start.setMonth(start.getMonth() + 2, 0);
}
return count;
}
console.log(countEOMDay(2019, 2019, 5)); // 1
console.log(countEOMDay(2018, 2019, 5)); // 3
You can use setMonth() method to set the month of a date object. The return value of setMonth() method is milliseconds between the date object and midnight January 1 1970. That's what you get from console.log(lastday);
Your return value,
1575093343211
is milliseconds between your date object (d) and midnight January 1 1970.
If you want to get the expected date, you have to console log your date object instead the lastday, as follows:
let d = new Date();
let month = d.getMonth()+1;
let lastday = d.setMonth(month, 0);
console.log(d);
output: Sat Nov 30 2019 00:02:47 GMT+0530 (India Standard Time)
This is an alternative solution I wrote to solve your problem. This will return the number of times a month ends with a Friday within a range of years. Hope this will help you :)
var days = [];
var count = 0;
function getLastFridaysCount(startYear, endYear) {
for (var year = startYear; year <= endYear; year++) {
days = [
31,
0 === year % 4 && 0 !== year % 100 || 0 === year % 400 ? 29 : 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
];
for (var month = 0; month <= 11; month++) {
var myDate = new Date();
myDate.setFullYear(year);
myDate.setMonth(month);
myDate.setDate(days[month]);
if(myDate.getDay() == 5)
{
count++;
}
}
}
return count;
}
console.log("count", getLastFridaysCount(2014, 2017));
this is the solution, in the code can find the comments "//" explaining of what happens in each iteration.
function lastDayIsFriday(initialYear, endYear) {
let count = 0;
//according to when the year ends starts the loop
if (endYear !== undefined) {
let start = new Date(initialYear, 0, 31);
let end = new Date(endYear, 11, 31);
while(start <= end) { //check if the start date is < or = to the end
//The getDay() method returns the day of the week (from 0 to 6) for the specified date.
if(start.getDay() === 5) { //if = to FriYAY!!!
count++; //count the day
}
start.setMonth(start.getMonth()+2, 0);// returns the month (from 0 to 11) .getMonth
} //& sets the month of a date object .setMonth
return count;
} else {
let start = new Date(initialYear, 0, 31);
console.log(start.toString());
for(let i = 0; i < 12; i++) {
if(start.getDay() === 5) {
count++;
}
start.setMonth(start.getMonth() + 2, 0);
// console.log(start.toString());
}
return count;
}
}
I need to find this month, previous month and the next month of a specific date.
For example, date was set to 31 of every month, what I expect to get the date is
2018-02-28, 2018-03-31 and 2018-04-30. For those dates which has no 31, than it becomes the day before.
And finally generate 2 period, 2018-02-28 to 2018-03-29, 2018-03-30 to 2018-04-31.
I don't know how to handle feb and the month which less than 31.
var d = new Date();
var tyear = d.getFullYear(); //2018
var tmonth = d.getMonth(); //2
new Date(2018, tmonth-1, 31);//output 2018-03-02 not what I wanted
A simple algorithm is to add months to the original date, and if the new date is wrong, set it to the last day of the previous month. Keeping the original date values unmodified helps, e.g.
/* #param {Date} start - date to start
** #param {number} count - number of months to generate dates for
** #returns {Array} monthly Dates from start for count months
*/
function getMonthlyDates(start, count) {
var result = [];
var temp;
var year = start.getFullYear();
var month = start.getMonth();
var startDay = start.getDate();
for (var i=0; i<count; i++) {
temp = new Date(year, month + i, startDay);
if (temp.getDate() != startDay) temp.setDate(0);
result.push(temp);
}
return result;
}
// Start on 31 Jan in leap year
getMonthlyDates(new Date(2016,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 31 Jan not in leap year
getMonthlyDates(new Date(2018,0,31), 4).forEach(d => console.log(d.toString()));
// Start on 30 Jan
getMonthlyDates(new Date(2018,0,30), 4).forEach(d => console.log(d.toString()));
// Start on 5 Jan
getMonthlyDates(new Date(2018,0,5), 4).forEach(d => console.log(d.toString()));
I think you're going to need an array with 12 numbers in it. Each number is the amount of days in each month and the numbers in the array go in order (first number is 31 because January has 31 days, second is 28 or 29 for Feb), etc. Then you'll get the month number from your input date and look in the array at the number corresponding to the month number +/- 1.
You'll then need to construct a date for the previous month and the next month based on the number of days in the current month.
See comments inline:
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
document.getElementById("date").addEventListener("input", function(){
console.clear();
// Create new Date based on value in date picker
var selectedDate = new Date(this.value + 'T00:00');
var year = selectedDate.getYear();
// Determine if it is a leap year (Feb has 29 days) and update array if so.
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
var selectedDateMonth = selectedDate.getMonth();
// Get previous month number (if current month is January, get December)
let prevMonth = selectedDateMonth > 0 ? selectedDateMonth - 1 : 11;
let prevMonthDate = null;
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
// Create new date that takes the selected date and subtracts the correct amount of
// days from it based on a lookup in the array.
var newDate1 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(newDate1.setDate(selectedDate.getDate() - daysInMonths[selectedDateMonth]));
} else {
// Create a new date that is last month and one day earlier
var newDate2 = new Date(selectedDate.getTime());
prevMonthDate =
new Date(new Date(newDate2.setDate(selectedDate.getDate() - 1))
.setMonth(selectedDate.getMonth() - 1));
}
// Get next month (if current month is December, get January
let nextMonth = selectedDateMonth < 11 ? selectedDateMonth + 1 : 0;
let nextMonthDate = null;
// Same idea for next month, but add instead of subtract.
// If selected date is last day of month...
if(selectedDate.getDate() === daysInMonths[selectedDateMonth]){
var newDate3 = new Date(selectedDate.getTime());
nextMonthDate =
new Date(newDate3.setDate(selectedDate.getDate() + daysInMonths[selectedDateMonth + 1]));
} else {
var newDate4 = new Date(selectedDate.getTime());
nextMonthDate = new Date(new Date(newDate4.setDate(selectedDate.getDate() + 1)).setMonth(selectedDate.getMonth() + 1));
}
console.log("Last month date: " + prevMonthDate.toLocaleDateString());
console.log("Next month date: " + nextMonthDate.toLocaleDateString());
});
<p>Pick a date: <input type="date" id="date"></p>
Use this approach:
Javascript Date Object – Adding and Subtracting Months
From the Author
There is a slight problem with the Javascript Date() Object when trying to advance to the next month or go back to the previous month.
For example, if your date is set to October 31, 2018 and you add one month, you'd probably expect the new date to be November 30, 2018 because November 31st doesn't exist. This, however, isn't the case.
Javascript automatically advances your Date object to December 1st. This functionality is very useful in most situations(i.e. adding days to a date, determining the number of days in a month or if it's a leap year), but not for adding/subtracting months. I've put together some functions below that extend the Date() object: nextMonth() and prevMonth().
function prevMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth - 1);
if (this.getMonth() != thisMonth - 1 && (this.getMonth() != 11 || (thisMonth == 11 && this.getDate() == 1)))
this.setDate(0);
}
function nextMonth() {
var thisMonth = this.getMonth();
this.setMonth(thisMonth + 1);
if (this.getMonth() != thisMonth + 1 && this.getMonth() != 0)
this.setDate(0);
}
Date.prototype.nextMonth = nextMonth;
Date.prototype.prevMonth = prevMonth;
var today = new Date(2018, 2, 31); //<----- March 31st, 2018
var prevMonth = new Date(today.getTime());
prevMonth.prevMonth();
console.log("Previous month:", prevMonth);
console.log("This month:", today)
var nextMonth = new Date(today.getTime());
nextMonth.nextMonth();
console.log("Next month:", nextMonth);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Dates and time zones are a real pain in JS, so challenge accepted.
I broke it down in two steps:
- Count the days of prev and next month
- Compare with selected day and pick the lowest number
Testcases included
function createUTCDate(year, month, day) {
return new Date(Date.UTC(year, month, day));
}
function splitDate(date) {
return {
year: date.getUTCFullYear(),
month: date.getUTCMonth(),
day: date.getUTCDate()
};
}
function numberOfDaysInMonth(year, month) {
return new Date(year, month + 1, 0).getDate();
}
function dateNextMonth(dateObj) {
const daysNextMonth = numberOfDaysInMonth(dateObj.year, dateObj.month + 1);
const day = Math.min(daysNextMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month + 1, day);
}
function datePreviousMonth(dateObj) {
const daysPrevMonth = numberOfDaysInMonth(dateObj.year, dateObj.month - 1);
const day = Math.min(daysPrevMonth, dateObj.day);
return createUTCDate(dateObj.year, dateObj.month - 1, day);
}
const log = console.log;
function print(dateString) {
const date = new Date(dateString);
const dateObj = splitDate(date);
log("Previous: ", datePreviousMonth(dateObj).toISOString());
log("Selected: ", date.toISOString());
log("Next: ", dateNextMonth(dateObj).toISOString());
log("--------------");
}
const testCases = [
"2018-03-01 UTC",
"2018-03-31 UTC",
"2018-01-01 UTC",
"2018-12-31 UTC"
];
testCases.forEach(print);
Please note that the hack with new Date(xxx + " UTC") is not according to spec and is just there for testing purposes. Results may vary per browser.
You should choose an input format and construct your dates accordingly.
I handle it in a foolish way by concatenating string
let daysInMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
var target = nexttarget = lasttarget = "29"; //target day
if (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)) {
daysInMonths[1] = 29;
}
function findLastDay(target, month){
if(target > daysInMonths[month]){
target = daysInMonths[month];
}
return target;
}
then
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
target = findLastDay(target, month);
var this_month = year+"-"+months[month]+"-"+target;
console.log(this_month);//2018-03-29
// next month
if(month == 11){
nextmonth = 0;
nextyear = year + 1;
}else{
nextmonth = month+1;
nextyear = year;
}
nexttarget = findLastDay(nexttarget, nextmonth);
var next_month = nextyear+"-"+months[nextmonth]+"-"+nexttarget;
console.log(next_month);//2018-04-29
//last month
if(month == 0){
lastmonth = 11;
lastyear = year - 1;
}else{
lastmonth = month - 1;
lastyear = year;
}
lasttarget = findLastDay(lasttarget, lastmonth);
var last_month = lastyear+"-"+months[lastmonth]+"-"+lasttarget;
console.log(last_month);//2018-02-28
Date handling is tricky at the best of times. Don't do this yourself. Use Moment.js.
var target = 31;
var today = moment().date(target).calendar();
// today == '03/31/2018'
var nextMonth = moment().date(target).add(1, 'month').calendar();
// nextMonth == '04/30/2018'
var lastMonth = moment().date(target).subtract(1, 'month').calendar()
// lastMonth == '02/28/2018'
I have a question about javascript time ranges
i have two input boxes, the client can give start date and end date
below have 3 seasons with date ranges,i need to count the cost for the user entered date range with
the mapping with below seasons with prices
Total is 3 seasons, below is the date ranges:
Low Season
1st May to 30th June
1st September to 14th December
Cost: $5 per day
High Season
11th January to 30th April
1st July to 31st August
Cost: $10 per day
Peak Season
-15th December - 10th January
Cost: $2 per day
i write a code for get the date inputs
$('#calculate').click(function(){
//get the first date
da=$('#daydropdowna').val();
ma=$('#monthdropdowna').val();
ya=$('#yeardropdowna').val();
//get the secnd date
dd=$('#daydropdownd').val();
md=$('#monthdropdownd').val();
yd=$('#yeardropdownd').val();
var oneDay = 24*60*60*1000;
var ourstart= new Date(ya,ma,da);
var oursend= new Date(yd,md,dd);
/*
11th January to 30th April
1st July to 31st August
*/
var hsstart= new Date(ya,00,11);
var hsend= new Date(ya,03,11);
var hsstart1= new Date(ya,06,01);
var hsend1= new Date(ya,07,31);
/*
1st May to 30th June
1st September to 14th December
*/
var lsstart=new Date(ya,04,01);
var lsend=new Date(ya,05,30);
var lsstart1=Date(ya,08,01);
var lsend1=new Date(ya,11,14);
/*
-15th December - 10th January
*/
var psstart=new Date(ya,11,15);
var psend=new Date(ya+1,00,10);
var myDate = ourstart;
var myDate1 = oursend;
var startDate = hsstart
var endDate = hsend
//the date range within one high season
if ((startDate < myDate) && (myDate < endDate) && (startDate < myDate1) && (myDate1 < endDate)) {
alert('seasn 1 h');
var diffDays = Math.round(Math.abs((myDate1 .getTime() - myDate .getTime())/(oneDay)));
alert (diffDays);
}
//the date range within secnd high season
var startDate = hsstart1
var endDate = hsend1
if ((startDate < myDate) && (myDate < endDate) && (startDate < myDate1) && (myDate1 < endDate)) {
alert('seasn 2 h');
var diffDays = Math.round(Math.abs((myDate1 .getTime() - myDate .getTime())/(oneDay)));
alert (diffDays);
}
//the date range within first low season
var startDate = lsstart
var endDate = lsend
if ((startDate < myDate) && (myDate < endDate) && (startDate < myDate1) && (myDate1 < endDate)) {
alert('season 1 l');
var diffDays = Math.round(Math.abs((myDate1 .getTime() - myDate .getTime())/(oneDay)));
alert (diffDays);
}
//the date range within second low season
var startDate = lsstart1
var endDate = lsend1
if ((startDate < myDate) && (myDate < endDate) && (startDate < myDate1) && (myDate1 < endDate)) {
alert('season 2 l');
var diffDays = Math.round(Math.abs((myDate1 .getTime() - myDate .getTime())/(oneDay)));
alert (diffDays);
}
//peak
var startDate = psstart
var endDate = psend
if ((startDate < myDate) && (myDate < endDate) && (startDate < myDate1) && (myDate1 < endDate)) {
alert('season p');
var diffDays = Math.round(Math.abs((myDate1 .getTime() - myDate .getTime())/(oneDay)));
alert (diffDays);
}
//if not wihin a specific range cacuate for all
});
so i need to calculate the total price according to the user input, Ex user enters 2012-05-05 - 2013-01-05 this need to calculate price for 3 season dates which is covering the date range. please hep me for solve this problem, thank you...
I'm not going to code for you but here's the logic:
tempDate = inputStartDate
for each season
if seasonStart <= tempDate
if inputEndDate <= seasonEnd
price = price + (inputEndDate - tempDate) * seasonCost
break
else
price = price + (seasonEnd - tempDate) * seasonCost
tempDate = seasonEnd + 1 day
price will contain the total cost/day for the entire date range.
What you need here, it sounds like, is a little help breaking down your work ;)
I think how I would attack this problem is design a custom dateRangeDistance function. You want to give a start date and find out how many days before one of your range end dates that day is, and then give an end date and calculate how many days ahead of what date range its in. I would also define your date ranges as maps rather than those nasty assortments of variables.
var peakSeason = {startDate: w/e, endDate: w/e, numDays: w/e, costRatePerDay: w/e}
var lowSeason1 = {startDate: w/e, endDate: w/e, numDays: w/e, costRatePerDay: w/e}
var lowSeason2 = {startDate: w/e, endDate: w/e, numDays: w/e, costRatePerDay: w/e}
// .... etc
var allSeasons = [peakSeason, lowSeason1, ...] // put these in order and it can help iterating date ranges between
var numberDaysStartFromEndOfRange = function(startDate) {
// iterate through the allSeasons map and find what range this is in
// return {numDays: whateverYouCalculate, dateRange: name your date ranges uniquely}
}
var numberDaysEndFromStartOfRange = function(startDate) {
// iterate through the allSeasons map and find what range this is in
// return {numDays: whateverYouCalculate, dateRange: name your date ranges uniquely}
}
Really you could make those functions the same function and pass a second param for whether you're counting from the front or back. This should put you on the right track though. If you need more help you can ask, but you do also need to understand that this is not a site that writes your algorithms for you ;)
Bottom line: leverage some helper functions and mappings of data structures to help break the work down into more manageable chunks!
I get three variables through a user input, that contain the year of a date, the month and the day. I've already checked if the month var is between 1–12 and so on.
Now I want to check if it's a real date and not a date that doesn't exist like 31–06–2011.
My first idea was to make a new Date instance:
var year = 2011;
var month = 5; // five because the months start with 0 in JavaScript - June
var day = 31;
var myDate = new Date(2011,5,31);
console.log(myDate);
But myDate doesn't return false, because it's not a valid date. Instead it returns 'Fri Jul 01 2011 [...]'.
Any ideas how I can check for an invalid date?
Try this:
if ((myDate.getMonth()+1!=month)||(myDate.getDate()!=day)||(myDate.getFullYear()!=year))
alert("Date Invalid.");
if ((myDate.getDate() != day) ||
(myDate.getMonth() != month - 1) ||
(myDate.getFullYear() != year))
{
return false;
}
JavaScript just converts entered in Date constructor month, year, day, etc.. in simple int value (milliseconds) and then formats it to represent in string format. You can create new Date(2011, 100, 100) and everythig will ok :)
You could possibly do what you do now and construct a new Date object and then afterwards check the value of myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), to ensure that those values match the input values. Keep in mind that getMonth() and getDate() are 0 indexed, so January is month 0 and December is month 11.
Here's an example:
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
}
console.log(isValidDate(2011,5,31));
console.log(isValidDate(2011,5,30));
This is a old question question however to help me and other after me, here is a php checkdate solution from the following webpage:
https://locutus.io/php/datetime/checkdate/
function checkdate (m, d, y) {
return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0))
.getDate()
}
I think this the right way to do it:
function isValidDate(year, month, day) {
var d = new Date(year, month, day)
if (month == 12) {
year = parseInt(year) * 1 + 1 * 1
month = 0
}
day = parseInt(day)
month = parseInt(month)
year = parseInt(year)
if (month === 2 && day > 29) {
return false
}
return (
d.getFullYear() === year && d.getMonth() === month && d.getDate() === day
)
}