How to calculate new date after date validation? - javascript

I'm using Elian Ebbing's data validation code from here and after validation, I'd like to take the date entered and return a new date for X amount of months later. For example, if I entered 06/09/2019, I would then like the code to return the correct new date that's 6 months later, which would be 12/6/2019.
Can someone please help guide me through the process of accomplishing this? I have been trying different methods of reusing the original code to get the results that I want, however I have been at this since July 2nd and have concluded I just can't figure this out on my own. I am completely stumped.
Lastly, my deepest apologies in advance that I didn't just comment on the original thread for Mr. Ebbing's code and ask for help, but unfortunately I did not have enough reputation points to do so.

If you are not sure that it is good to use some library (moment.js). If you want to find something already discovered, be ready to bump your head.
// Elian Ebbing validator
function isValidDate(dateString) {
// First check for the pattern
if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
return false;
// Parse the date parts to integers
var parts = dateString.split("/");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if(year < 1000 || year > 3000 || month == 0 || month > 12)
return false;
var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
// Adjust for leap years
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
// if you want to change date format
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1), // monts start form 0 so for result 06/01/2019
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [month, day, year].join('/');
}
// increment Date with count of months
function incrementDate(date, counter = 0) {
if (isValidDate(start_date_value)) {
var newDate = new Date(date);
newDate.setMonth(newDate.getMonth() + counter);
console.log(formatDate(newDate));
}
}
var start_date_value = "01/01/2019";
incrementDate(start_date_value, 5) ; // 06/01/2019

Related

Can I use comparison and logical operators for time inputs in Javascript? [duplicate]

I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}

birth date input not working after number 13 with javascript

We are doing AB testing. We can only touch the client side code with Google Optimize. So the designer asked us to change the birth date format from separated input to an unify input like this ->
So the idea is that the user type the birth date numbers [13.07.1998] and then the information will get to the separated input like this [13] [July] [1998]
It works fine until we use day 13. After that number the code does not work. But if I use 12 it works.
const dobInput = document.querySelector("input");
const birthDay = document.querySelector("#birthDay");
const birthMonth = document.querySelector("#birthMonth");
const birthYear = document.querySelector("#birthYear");
dobInput.addEventListener("change", (e) => {
const dobString = e.target.value;
if ( isValidDate(dobString) ) {
let date = dobString.slice(0, 2);
let month = dobString.slice(3, 5);
let year = dobString.slice(6, 10);
birthDay.value = date;
birthMonth.value = month;
birthYear.value = year;
} else {
const errorMessage = document.querySelector(".cro-error-text");
errorMessage.classList.add('error');
}
});
function isValidDate(dateString) {
// First check for the pattern
if (!/^\d{1,2}\.\d{1,2}\.\d{4}$/.test(dateString)) return false;
// Parse the date parts to integers
var parts = dateString.split(".");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
var year = parseInt(parts[2], 10);
// Check the ranges of month and year
if (year < 1905 || year > 2004 || month == 0 || month > 12) return false;
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Adjust for leap years
if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
monthLength[1] = 29;
// Check the range of the day
return day > 0 && day <= monthLength[month - 1];
}
Does anyone knows why it could be happening? thanks!
I think the error is this....
if-----------------------------------------
12 - - - 10 - - - 2000
Day - - - month - - - year
in your code you are saving
12 - - - - 10 - - - 2000
Month - - -Day - - - -year
I think the error is this because I think you are using selects tag.
select tags have options tag....and each option tag have a value.
<select>
<option value=1>Jenuary</option>
<option value=2>February</option>
</select>
So _select.value=13 is not posible.because there shouldn't be an
<option value=13>
There is not a month 13...I think you are confusing month with day when you store it in the variable
Or check if all options tags are within select tag...

How to get a specify date in every month in Javascript?

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'

How do I convert a decimal year value into a Date in Javascript?

OK, this is basically a Javascript version of How can I convert a decimal year value into a Date in Ruby? and not exactly a duplicate of Javascript function to convert decimal years value into years, months and days
Input:
2015.0596924
Desired output:
January 22, 2015
I have solved it (see below), but I expect (just like the Ruby version of this question) that there is a better way.
The other solution would be:
Create date for given year (integer part)
Calculate days from reminder (decimal part) and convert to milliseconds
Add milliseconds to (1)
In script:
function leapYear(year) {
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
};
function convertDecimalDate(decimalDate) {
var year = parseInt(decimalDate);
var reminder = decimalDate - year;
var daysPerYear = leapYear(year) ? 366 : 365;
var miliseconds = reminder * daysPerYear * 24 * 60 * 60 * 1000;
var yearDate = new Date(year, 0, 1);
return new Date(yearDate.getTime() + miliseconds);
}
var date = convertDecimalDate(2015.0596924);
console.log(date);
You can play with it on this Fiddle.
JavaScript will resolve the dates for you if you add too much time. See demonstration below. The solution below doesn't calculate the leap year based on the algorithm, but takes next year's date and subtracts it from this year. This assumes that the JavaScript specification properly calculates leap years.
See Mozilla Docs for more info.
function decimalDateToJsDate(time) {
var year = Math.floor(time);
var thisYear = new Date(year, 0, 1);
var nextYear = new Date(year + 1, 0, 1);
var millisecondsInYear = nextYear.getTime() - thisYear.getTime();
var deltaTime = Math.ceil((time - year) * millisecondsInYear);
thisYear.setMilliseconds(deltaTime);
return thisYear;
}
document.getElementById("output").innerHTML = decimalDateToJsDate(2015.0596924);
<pre id="output"></pre>
function leapYear (year){
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function getMonthAndDayFromDayOfYear(dayOfYear, year){
var daysInMonthArray = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (leapYear(year)) { daysInMonthArray[2] = 29; }
var daysLeft = dayOfYear;
var month = 0;
for (i=0; i<daysInMonthArray.length; i++) {
var daysInThisMonth = daysInMonthArray[i];
if (daysLeft > daysInThisMonth) {
month += 1;
daysLeft -= daysInThisMonth;
} else {
break;
}
}
return { month: month, day: daysLeft };
}
function convertDecimalDate(decimalDate){
decimalDate = parseFloat(decimalDate);
var year = parseInt(decimalDate); // Get just the integer part for the year
var daysPerYear = leapYear(year) ? 366 : 365; // Set days per year based on leap year or not
var decimalYear = decimalDate - year; // A decimal representing portion of the year left
var dayOfYear = Math.ceil(decimalYear * daysPerYear); // day of Year: 1 to 355 (or 366)
var md = getMonthAndDayFromDayOfYear(dayOfYear, year);
var day = md['day'];
var month = md['month'];
return new Date(year,month,day);
}
var date = convertDecimalDate(2015.0596924);

How to validate a date?

I'm trying to test to make sure a date is valid in the sense that if someone enters 2/30/2011 then it should be wrong.
How can I do this with any date?
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[1] - 1, bits[0]);
return d && (d.getMonth() + 1) == bits[1];
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate(s))
})
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {
var bits = s.split('/');
var y = bits[2],
m = bits[1],
d = bits[0];
// Assume not leap year by default (note zero index for Jan)
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// If evenly divisible by 4 and not evenly divisible by 100,
// or is evenly divisible by 400, then a leap year
if ((!(y % 4) && y % 100) || !(y % 400)) {
daysInMonth[1] = 29;
}
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]
}
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {
console.log(s + ' : ' + isValidDate2(s))
})
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'?
I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid() gives desired result.
Se post HERE
This solution does not address obvious date validations such as making sure date parts are integers or that date parts comply with obvious validation checks such as the day being greater than 0 and less than 32. This solution assumes that you already have all three date parts (year, month, day) and that each already passes obvious validations. Given these assumptions this method should work for simply checking if the date exists.
For example February 29, 2009 is not a real date but February 29, 2008 is. When you create a new Date object such as February 29, 2009 look what happens (Remember that months start at zero in JavaScript):
console.log(new Date(2009, 1, 29));
The above line outputs: Sun Mar 01 2009 00:00:00 GMT-0800 (PST)
Notice how the date simply gets rolled to the first day of the next month. Assuming you have the other, obvious validations in place, this information can be used to determine if a date is real with the following function (This function allows for non-zero based months for a more convenient input):
var isActualDate = function (month, day, year) {
var tempDate = new Date(year, --month, day);
return month === tempDate.getMonth();
};
This isn't a complete solution and doesn't take i18n into account but it could be made more robust.
var isDate_ = function(input) {
var status = false;
if (!input || input.length <= 0) {
status = false;
} else {
var result = new Date(input);
if (result == 'Invalid Date') {
status = false;
} else {
status = true;
}
}
return status;
}
this function returns bool value of whether the input given is a valid date or not. ex:
if(isDate_(var_date)) {
// statements if the date is valid
} else {
// statements if not valid
}
I just do a remake of RobG solution
var daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
var isLeap = new Date(theYear,1,29).getDate() == 29;
if (isLeap) {
daysInMonth[1] = 29;
}
return theDay <= daysInMonth[--theMonth]
This is ES6 (with let declaration).
function checkExistingDate(year, month, day){ // year, month and day should be numbers
// months are intended from 1 to 12
let months31 = [1,3,5,7,8,10,12]; // months with 31 days
let months30 = [4,6,9,11]; // months with 30 days
let months28 = [2]; // the only month with 28 days (29 if year isLeap)
let isLeap = ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
let valid = (months31.indexOf(month)!==-1 && day <= 31) || (months30.indexOf(month)!==-1 && day <= 30) || (months28.indexOf(month)!==-1 && day <= 28) || (months28.indexOf(month)!==-1 && day <= 29 && isLeap);
return valid; // it returns true or false
}
In this case I've intended months from 1 to 12. If you prefer or use the 0-11 based model, you can just change the arrays with:
let months31 = [0,2,4,6,7,9,11];
let months30 = [3,5,8,10];
let months28 = [1];
If your date is in form dd/mm/yyyy than you can take off day, month and year function parameters, and do this to retrieve them:
let arrayWithDayMonthYear = myDateInString.split('/');
let year = parseInt(arrayWithDayMonthYear[2]);
let month = parseInt(arrayWithDayMonthYear[1]);
let day = parseInt(arrayWithDayMonthYear[0]);
My function returns true if is a valid date otherwise returns false :D
function isDate (day, month, year){
if(day == 0 ){
return false;
}
switch(month){
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
if(day > 31)
return false;
return true;
case 2:
if (year % 4 == 0)
if(day > 29){
return false;
}
else{
return true;
}
if(day > 28){
return false;
}
return true;
case 4: case 6: case 9: case 11:
if(day > 30){
return false;
}
return true;
default:
return false;
}
}
console.log(isDate(30, 5, 2017));
console.log(isDate(29, 2, 2016));
console.log(isDate(29, 2, 2015));
It's unfortunate that it seems JavaScript has no simple way to validate a date string to these days. This is the simplest way I can think of to parse dates in the format "m/d/yyyy" in modern browsers (that's why it doesn't specify the radix to parseInt, since it should be 10 since ES5):
const dateValidationRegex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
function isValidDate(strDate) {
if (!dateValidationRegex.test(strDate)) return false;
const [m, d, y] = strDate.split('/').map(n => parseInt(n));
return m === new Date(y, m - 1, d).getMonth() + 1;
}
['10/30/2000abc', '10/30/2000', '1/1/1900', '02/30/2000', '1/1/1/4'].forEach(d => {
console.log(d, isValidDate(d));
});
Hi Please find the answer below.this is done by validating the date newly created
var year=2019;
var month=2;
var date=31;
var d = new Date(year, month - 1, date);
if (d.getFullYear() != year
|| d.getMonth() != (month - 1)
|| d.getDate() != date) {
alert("invalid date");
return false;
}
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}

Categories