Javascript Calculating year diff error in date? - javascript

I am trying to understand the date in JavaScript. But I can't get it.
I create a function that takes two dates and returns a value based on the difference of dates.
Here is the whole code:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff = 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = new Date(dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim());
let dld = new Date(dl_string.substr(dl_string.indexOf("Download") + 14, 11).trim());
console.log(checkDate(dob,dld));
The is the date is not getting created it says Invalid Date.
I want to check if the DOB difference is 5 more or not.

The problem is the new Date constructor doesn't understand dd/mm/yyyy format and is implemented differently on different browsers. What you need to do is convert it into valid format.
One way is to split it and pass into the constructor like this:
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
let dob = dob_string.substr(dob_string.indexOf("DOB:") + 4, 11).trim();
const splitDOB = dob.split('/')
const validDate = new Date(
parseInt(splitDOB[2], 10),
parseInt(splitDOB[1], 10) - 1,
parseInt(splitDOB[0], 10)
);
The - 1 in the second param is because month is 0-indexed. Then you can process with the logic of your own function.
But I highly recommend using 3rd party lib such as dayjs when working with date/time in JS

so i tested it and even the substrings creates invalid dates.
so i wrote you this:
function checkDate(birth_date, download_date) {
let yearDiff = download_date.getFullYear() - birth_date.getFullYear();
console.log(yearDiff);
if (yearDiff > 5) return "Not Eligible";
if (yearDiff < 5) return "Eligible";
if (yearDiff == 5) {
// Eligible only if 5 years or low
// If diff is Exact 5 Years Check if Bday is on download date ?
// First Check Month
let monthDiff = download_date.getMonth() - birth_date.getMonth();
if (monthDiff >= 1) {
return "Not Eligible"
}
if (monthDiff <= -1) {
return "Eligible"
}
if (monthDiff == 0) {
// Check Day
let dateDiff = download_date.getDay() - birth_date.getDay();
if (dateDiff <= 0) {
return "Eligible"
} else {
return "Not Eligible"
}
}
}
}
let dob_string = "DOB: 14/09/2016";
let dl_string = "Download Date: 03/11/2020";
function filterDate(str) {
const match = str.match(/(\d{1,2}).(\d{1,2}).(\d{4})/);
let year = match[3];
let month = match[2];
let day = match[1];
if (isNaN(year) || isNaN(month) || isNaN(day)) {
throw new Error("no valid date");
}
// fix strings to numbers;
year = +year;
month = +month;
day = +day;
// months begins on 0
month = month - 1;
return new Date(year, month, day);
}
console.log(checkDate(filterDate(dob_string),filterDate(dl_string)));

Related

validate a date in dd/mm/yyyy format

I am trying to validate a date with regex but its failing, i am trying to use it to write it in input manually or select from a calendar on the side
<input type="text" name="FromDate" value="28/8/2022" id="Strtcalfield1" REQUIRED="yes" VALIDATE="date" MESSAGE="Please enter date (dd/MM/yyyy)." pattern="/^(\s{0,})(\d{2}\/\d{2}\/\d{4})(,\d{2}\/\d{2}\/\d{4}){1,}(\s){0,}$" oninvalid="this.setCustomValidity('Please enter date (dd/mm/yyyy).')" oninput="this.setCustomValidity('')"/>
and that is throwing an error
value is coming from backend, but when i choose rom calendar, it keeps on giving me an error
please enter date as dd/mm/yyyy as i see the date is correctly entered
You could validate the string with a JavaScript function instead of the regex pattern to ensure that it is a valid date. The following function parses the dd/mm/yyyy string pattern and ensures the day part is in the correct range for the parsed month and year values.
function validateDateString(dateString) {
// regex for date string format: dd/mm/yyyy
const dateFormatRegex = /^(0?[1-9]|[1-2][0-9]|3[01])[\/](0?[1-9]|1[0-2])[\/]\d{4}$/;
let isValidDate = false;
if (dateString.match(dateFormatRegex)) {
const dateParts = dateString.split('/');
if (dateParts.length == 3) {
const day = parseInt(dateParts[0]);
const month = parseInt(dateParts[1]);
const year = parseInt(dateParts[2]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
isValidDate = true;
}
}
return isValidDate;
}
EDIT: The following modifications will allow the code to handle the date format of the locale used in the browser.
The getLocaleDateFormat function determines the locale date format by generating a unique date and identifying the position of each element in the locale string. The date separator character is also identified and the information is returned in a single object with keys: day, month, year and sep.
function getLocaleDateFormat() {
const dummyDate = new Date(1999,11,30).toLocaleDateString().replace(/1999/,"yyyy").replace(/30/,"dd").replace(/12/,"mm");
const findDateSegmentIndex = (pos) => {
let index = -1;
if (pos == 0) {
index = 0;
}
else if ((pos > 0) & (pos < 6)) {
index = 1;
}
else if ((pos > 5) & (pos < 10)) {
index = 2;
}
return index;
};
const localeInfo = {
"day": findDateSegmentIndex(dummyDate.search("dd")),
"month": findDateSegmentIndex(dummyDate.search("mm")),
"year": findDateSegmentIndex(dummyDate.search("yyyy")),
"sep": dummyDate[dummyDate.search(/\W/)]
};
return localeInfo;
}
The getDateStringFormat function uses the information in the object returned by getLocaleDateFormat() to assemble a string to create the regular expression which will match the locale date format. The object returned by the function includes the regular expression string in the regex key.
function getDateStringFormat() {
const dateLocale = getLocaleDateFormat();
const regexStringsObject = {
"day": '(0?[1-9]|[1-2][0-9]|3[01])',
"month": '(0?[1-9]|1[0-2])',
"year": '\\d{4}'
}
let regexElements = ['', '', ''];
regexElements[ dateLocale["day"] ] = regexStringsObject["day"];
regexElements[ dateLocale["month"] ] = regexStringsObject["month"];
regexElements[ dateLocale["year"] ] = regexStringsObject["year"];
const dateStringFormat = { ...dateLocale,
"regex": `^${regexElements[0]}[.\\-\\/]${regexElements[1]}[.\\-\\/]${regexElements[2]}$`
};
return dateStringFormat;
}
The updated validateDateString function uses the regex string in the object returned by getDateStringFormat() to parse the provided dateString. There are three different separators (-, ., /) handled. The locale date format information as determined in the getLocaleDateFormat function is used to validate the respective part of the date string.
function validateDateString(dateString) {
const dateFormat = getDateStringFormat();
let result = false;
const regex = new RegExp(dateFormat.regex);
if (dateString.match(regex)) {
const dateParts = dateString.split(/[.\-\/]/);
if (dateParts.length == 3) {
const day = parseInt(dateParts[dateFormat.day]);
const month = parseInt(dateParts[dateFormat.month]);
const year = parseInt(dateParts[dateFormat.year]);
// valid month range is 1 - 12
if (month < 1 || month > 12) {
return false;
}
// validate days in month
const daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
let monthLength = daysInMonth[month-1];
if ((month == 2) && ((!(year%4) && year%100) || !(year%400))) {
monthLength = 29;
}
if (day < 1 || day > monthLength) {
return false;
}
// checks have passed
result = true;
}
}
return result;
}

In IE date is retrieved as NaN [duplicate]

I'm trying to build a little calendar in JavaScript. I have my dates working great in Firefox and Chrome, but in IE the date functions are returning NaN.
Here is the function :
function buildWeek(dateText){
var headerDates='';
var newDate = new Date(dateText);
for(var d=0;d<7;d++){
headerDates += '<th>' + newDate + '</th>';
newDate.setDate(newDate.getDate()+1);
}
jQuery('div#headerDates').html('<table><tr>'+headerDates+'</tr></table>');
}
dateText is the Monday of the current week which is actually set in php in the format of 'm, d, Y', e.g. "02, 01, 2010".
From a mysql datetime/timestamp format:
var dateStr="2011-08-03 09:15:11"; //returned from mysql timestamp/datetime field
var a=dateStr.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date(d[0],(d[1]-1),d[2],t[0],t[1],t[2]);
I hope is useful for someone.
Works in IE FF Chrome
The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()
A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.
An example of that appears here:
http://jibbering.com/faq/#parseDate
ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.
Edit:
The entry from comp.lang.javascript FAQ is:
An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-
/**Parses string formatted as YYYY-MM-DD to a Date object.
* If the supplied string does not match the format, an
* invalid Date (value NaN) is returned.
* #param {string} dateStringInRange format YYYY-MM-DD, with year in
* range of 0000-9999, inclusive.
* #return {Date} Date object representing the string.
*/
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
Don't use "new Date()", because it takes the input date string as local time:
new Date('11/08/2010').getTime()-new Date('11/07/2010').getTime(); //90000000
new Date('11/07/2010').getTime()-new Date('11/06/2010').getTime(); //86400000
we should use "NewDate()", it takes the input as GMT time:
function NewDate(str)
{str=str.split('-');
var date=new Date();
date.setUTCFullYear(str[0], str[1]-1, str[2]);
date.setUTCHours(0, 0, 0, 0);
return date;
}
NewDate('2010-11-07').toGMTString();
NewDate('2010-11-08').toGMTString();
Here's another approach that adds a method to the Date object
usage: var d = (new Date()).parseISO8601("1971-12-15");
/**
* Parses the ISO 8601 formated date into a date object, ISO 8601 is YYYY-MM-DD
*
* #param {String} date the date as a string eg 1971-12-15
* #returns {Date} Date object representing the date of the supplied string
*/
Date.prototype.parseISO8601 = function(date){
var matches = date.match(/^\s*(\d{4})-(\d{2})-(\d{2})\s*$/);
if(matches){
this.setFullYear(parseInt(matches[1]));
this.setMonth(parseInt(matches[2]) - 1);
this.setDate(parseInt(matches[3]));
}
return this;
};
I always store my date in UTC time.
This is my own function made from the different functions I found in this page.
It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.
This function return a timestamp.
The DATETIME is considered as a UTC date.
Be carefull : If you expect a local datetime, this function is not for you.
function datetimeToTimestamp(datetime)
{
var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
if(regDatetime.test(datetime) === false)
throw("Wrong format for the param. `Y-m-d H:i:s` expected.");
var a=datetime.split(" ");
var d=a[0].split("-");
var t=a[1].split(":");
var date = new Date();
date.setUTCFullYear(d[0],(d[1]-1),d[2]);
date.setUTCHours(t[0],t[1],t[2], 0);
return date.getTime();
}
Here's a code snippet that fixes that behavior of IE
(v['date'] is a comma separated date-string, e.g. "2010,4,1"):
if($.browser.msie){
$.lst = v['date'].split(',');
$.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
$.tmp = new Date(v['date']);
}
The previous approach didn't consider that JS Date month is ZERO based...
Sorry for not explaining too much, I'm at work and just thought this might help.
Here's my approach:
var parseDate = function(dateArg) {
var dateValues = dateArg.split('-');
var date = new Date(dateValues[0],dateValues[1],dateValues[2]);
return date.format("m/d/Y");
}
replace ('-') with the delimeter you're using.
Send the date text and format in which you are sending the datetext in the below method. It will parse and return as date and this is independent of browser.
function cal_parse_internal(val, format) {
val = val + "";
format = format + "";
var i_val = 0;
var i_format = 0;
var x, y;
var now = new Date(dbSysCurrentDate);
var year = now.getYear();
var month = now.getMonth() + 1;
var date = now.getDate();
while (i_format < format.length) {
// Get next token from format string
var c = format.charAt(i_format);
var token = "";
while ((format.charAt(i_format) == c) && (i_format < format.length)) {
token += format.charAt(i_format++);
}
// Extract contents of value based on format token
if (token == "yyyy" || token == "yy" || token == "y") {
if (token == "yyyy") { x = 4; y = 4; }
if (token == "yy") { x = 2; y = 2; }
if (token == "y") { x = 2; y = 4; }
year = _getInt(val, i_val, x, y);
if (year == null) { return 0; }
i_val += year.length;
if (year.length == 2) {
if (year > 70) {
year = 1900 + (year - 0);
} else {
year = 2000 + (year - 0);
}
}
} else if (token == "MMMM") {
month = 0;
for (var i = 0; i < MONTHS_LONG.length; i++) {
var month_name = MONTHS_LONG[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MMM") {
month = 0;
for (var i = 0; i < MONTHS_SHORT.length; i++) {
var month_name = MONTHS_SHORT[i];
if (val.substring(i_val, i_val + month_name.length) == month_name) {
month = i + 1;
i_val += month_name.length;
break;
}
}
if (month < 1 || month > 12) { return 0; }
} else if (token == "MM" || token == "M") {
month = _getInt(val, i_val, token.length, 2);
if (month == null || month < 1 || month > 12) { return 0; }
i_val += month.length;
} else if (token == "dd" || token == "d") {
date = _getInt(val, i_val, token.length, 2);
if (date == null || date < 1 || date > 31) { return 0; }
i_val += date.length;
} else {
if (val.substring(i_val, i_val+token.length) != token) {return 0;}
else {i_val += token.length;}
}
}
// If there are any trailing characters left in the value, it doesn't match
if (i_val != val.length) { return 0; }
// Is date valid for month?
if (month == 2) {
// Check for leap year
if ((year%4 == 0 && year%100 != 0) || (year%400 == 0)) { // leap year
if (date > 29) { return false; }
} else {
if (date > 28) { return false; }
}
}
if (month == 4 || month == 6 || month == 9 || month == 11) {
if (date > 30) { return false; }
}
return new Date(year, month - 1, date);
}
The Date constructor in JavaScript needs a string in one of the date formats supported by the parse() method.
Apparently, the format you are specifying isn't supported in IE, so you'll need to either change the PHP code, or parse the string manually in JavaScript.
You can use the following code to parse ISO8601 date string:
function parseISO8601(d) {
var timestamp = d;
if (typeof (d) !== 'number') {
timestamp = Date.parse(d);
}
return new Date(timestamp);
};
Try out using getDate feature of datepicker.
$.datepicker.formatDate('yy-mm-dd',new Date(pField.datepicker("getDate")));
I tried all the above solution but nothing worked for me.
I did some brainstorming and found this and worked fine in IE11 as well.
value="2020-08-10 05:22:44.0";
var date=new Date(value.replace(" ","T")).$format("d/m/yy h:i:s");
console.log(date);
if $format is not working for you use format only.

Check if Saturday and Sunday exist between two days in Javascript [duplicate]

Wondering if anyone has a solution for checking if a weekend exist between two dates and its range.
var date1 = 'Apr 10, 2014';
var date2 = 'Apr 14, 2014';
funck isWeekend(date1,date2){
//do function
return isWeekend;
}
Thank you in advance.
EDIT Adding what I've got so far. Check the two days.
function isWeekend(date1,date2){
//do function
if(date1.getDay() == 6 || date1.getDay() == 0){
return isWeekend;
console.log("weekend")
}
if(date2.getDay() == 6 || date2.getDay() == 0){
return isWeekend;
console.log("weekend")
}
}
Easiest would be to just iterate over the dates and return if any of the days are 6 (Saturday) or 0 (Sunday)
Demo: http://jsfiddle.net/abhitalks/xtD5V/1/
Code:
function isWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2),
isWeekend = false;
while (d1 < d2) {
var day = d1.getDay();
isWeekend = (day === 6) || (day === 0);
if (isWeekend) { return true; } // return immediately if weekend found
d1.setDate(d1.getDate() + 1);
}
return false;
}
If you want to check if the whole weekend exists between the two dates, then change the code slightly:
Demo 2: http://jsfiddle.net/abhitalks/xtD5V/2/
Code:
function isFullWeekend(date1, date2) {
var d1 = new Date(date1),
d2 = new Date(date2);
while (d1 < d2) {
var day = d1.getDay();
if ((day === 6) || (day === 0)) {
var nextDate = d1; // if one weekend is found, check the next date
nextDate.setDate(d1.getDate() + 1); // set the next date
var nextDay = nextDate.getDay(); // get the next day
if ((nextDay === 6) || (nextDay === 0)) {
return true; // if next day is also a weekend, return true
}
}
d1.setDate(d1.getDate() + 1);
}
return false;
}
You are only checking if the first or second date is a weekend day.
Loop from the first to the second date, returning true only if one of the days in between falls on a weekend-day:
function isWeekend(date1,date2){
var date1 = new Date(date1), date2 = new Date(date2);
//Your second code snippet implies that you are passing date objects
//to the function, which differs from the first. If it's the second,
//just miss out creating new date objects.
while(date1 < date2){
var dayNo = date1.getDay();
date1.setDate(date1.getDate()+1)
if(!dayNo || dayNo == 6){
return true;
}
}
}
JSFiddle
Here's what I'd suggest to test if a weekend day falls within the range of two dates (which I think is what you were asking):
function containsWeekend(d1, d2)
{
// note: I'm assuming d2 is later than d1 and that both d1 and d2 are actually dates
// you might want to add code to check those conditions
var interval = (d2 - d1) / (1000 * 60 * 60 * 24); // convert to days
if (interval > 5) {
return true; // must contain a weekend day
}
var day1 = d1.getDay();
var day2 = d2.getDay();
return !(day1 > 0 && day2 < 6 && day2 > day1);
}
fiddle
If you need to check if a whole weekend exists within the range, then it's only slightly more complicated.
It doesn't really make sense to pass in two dates, especially when they are 4 days apart. Here is one that only uses one day which makes much more sense IMHO:
var date1 = 'Apr 10, 2014';
function isWeekend(date1){
var aDate1 = new Date(date1);
var dayOfWeek = aDate1.getDay();
return ((dayOfWeek == 0) || (dayOfWeek == 6));
}
I guess this is the one what #MattBurland sugested for doing it without a loop
function isWeekend(start,end){
start = new Date(start);
if (start.getDay() == 0 || start.getDay() == 6) return true;
end = new Date(end);
var day_diff = (end - start) / (1000 * 60 * 60 * 24);
var end_day = start.getDay() + day_diff;
if (end_day > 5) return true;
return false;
}
FIDDLE
Whithout loops, considering "sunday" first day of week (0):
Check the first date day of week, if is weekend day return true.
SUM "day of the week" of the first day of the range and the number of days in the lap.
If sum>5 return true
Use Date.getDay() to tell if it is a weekend.
if(tempDate.getDay()==6 || tempDate.getDay()==0)
Check this working sample:
http://jsfiddle.net/danyu/EKP6H/2/
This will list out all weekends in date span.
Modify it to adapt to requirements.
Good luck.

How to exclude weekends between two dates using Moment.js

I am trying to exclude weekends in my JavaScript code. I use moment.js and having difficulty choosing the right variable for 'days'.
So far I have thought that I need to exclude day 6 (saturday) and day 0 (sunday) by changing the weekday variable to count from day 1 to day 5 only. But not sure how it changes.
My jsfiddle is shown here: FIDDLE
HTML:
<div id="myContent">
<input type="radio" value="types" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping1">Free Shipping: (<span id="fsv1" value="5">5</span> to <span id="fsv2" value="10">10</span> working days)</label> </td><br>
<div id="contacts" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative;margin-bottom:25px;">
Contacts
</div>
<input type="radio" value="groups" class="syncTypes" name="syncTypes"> <td><label for="xshipping.xshipping2">Express Shipping: (<span id="esv1" value="3">3</span> to <span id="esv2" value="4">4</span> working days)</label> </td>
<div id="groups" style="display:none;border:1px #666 solid;padding:3px;top:15px;position:relative">
Groups
</div>
</div>
JavaScript:
var a = 5; //Free shipping between a
var b = 10;//and b
var c = 3;//Express shipping between c
var d = 4;//and d
var now = moment();
var f = "Your item will be delivered between " + now.add("days",a).format("Do MMMM") + " and " + now.add("days",b).format("Do MMMM");
var g = "Your item will be delivered between " + now.add("days".c).format("Do MMMM") + " and " + now.add("days",d).format("Do MMMM");
var h = document.getElementById('contacts');
h.innerHTML = g
var i = document.getElementById('groups');
i.innerHTML = f
$(function() {
$types = $('.syncTypes');
$contacts = $('#contacts');
$groups = $('#groups');
$types.change(function() {
$this = $(this).val();
if ($this == "types") {
$groups.slideUp(300);
$contacts.delay(200).slideDown(300);
}
else if ($this == "groups") {
$contacts.slideUp(300);
$groups.delay(200).slideDown(300);
}
});
});
Here you go!
function addWeekdays(date, days) {
date = moment(date); // use a clone
while (days > 0) {
date = date.add(1, 'days');
// decrease "days" only if it's a weekday.
if (date.isoWeekday() !== 6 && date.isoWeekday() !== 7) {
days -= 1;
}
}
return date;
}
You call it like this
var date = addWeekdays(moment(), 5);
I used .isoWeekday instead of .weekday because it doesn't depend on the locale (.weekday(0) can be either Monday or Sunday).
Don't subtract weekdays, i.e addWeekdays(moment(), -3) otherwise this simple function will loop forever!
Updated JSFiddle http://jsfiddle.net/Xt2e6/39/ (using different momentjs cdn)
Those iteration looped solutions would not fit my needs.
They were too slow for large numbers.
So I made my own version:
https://github.com/leonardosantos/momentjs-business
Hope you find it useful.
https://github.com/andruhon/moment-weekday-calc plugin for momentJS might be helpful for similar tasks
It does not solves the exact problem, but it is able to calculate specific weekdays in the range.
Usage:
moment().isoWeekdayCalc({
rangeStart: '1 Apr 2015',
rangeEnd: '31 Mar 2016',
weekdays: [1,2,3,4,5], //weekdays Mon to Fri
exclusions: ['6 Apr 2015','7 Apr 2015'] //public holidays
}) //returns 260 (260 workdays excluding two public holidays)
If you want a pure JavaScript version (not relying on Moment.js) try this...
function addWeekdays(date, days) {
date.setDate(date.getDate());
var counter = 0;
if(days > 0 ){
while (counter < days) {
date.setDate(date.getDate() + 1 ); // Add a day to get the date tomorrow
var check = date.getDay(); // turns the date into a number (0 to 6)
if (check == 0 || check == 6) {
// Do nothing it's the weekend (0=Sun & 6=Sat)
}
else{
counter++; // It's a weekday so increase the counter
}
}
}
return date;
}
You call it like this...
var date = addWeekdays(new Date(), 3);
This function checks each next day to see if it falls on a Saturday (day 6) or Sunday (day 0). If true, the counter is not increased yet the date is increased.
This script is fine for small date increments like a month or less.
I would suggest adding a function to the moment prototype.
Something like this maybe? (untested)
nextWeekday : function () {
var day = this.clone(this);
day = day.add('days', 1);
while(day.weekday() == 0 || day.weekday() == 6){
day = day.add("days", 1);
}
return day;
},
nthWeekday : function (n) {
var day = this.clone(this);
for (var i=0;i<n;i++) {
day = day.nextWeekday();
}
return day;
},
And when you're done and written some tests, send in a pull request for bonus points.
d1 and d2 are moment dates passed as an argument to calculateBusinessDays
calculateBusinessDays(d1, d2) {
const days = d2.diff(d1, "days") + 1;
let newDay: any = d1.toDate(),
workingDays: number = 0,
sundays: number = 0,
saturdays: number = 0;
for (let i = 0; i < days; i++) {
const day = newDay.getDay();
newDay = d1.add(1, "days").toDate();
const isWeekend = ((day % 6) === 0);
if (!isWeekend) {
workingDays++;
}
else {
if (day === 6) saturdays++;
if (day === 0) sundays++;
}
}
console.log("Total Days:", days, "workingDays", workingDays, "saturdays", saturdays, "sundays", sundays);
return workingDays;
}
If you want a version of #acorio's code sample which is performant (using #Isantos's optimisation) and can deal with negative numbers use this:
moment.fn.addWorkdays = function (days) {
// Getting negative / positive increment
var increment = days / Math.abs(days);
// Looping weeks for each full 5 workdays
var date = this.clone().add(Math.floor(Math.abs(days) / 5) * 7 * increment, 'days');
// Account for starting on Saturdays and Sundays
if(date.isoWeekday() === 6) { date.add(-increment, 'days'); }
else if(date.isoWeekday() === 7) { date.add(-2 * increment, 'days'); }
// Adding / removing remaining days in a short loop, jumping over weekends
var remaining = days % 5;
while(remaining != 0) {
date.add(increment, 'days');
if(date.isoWeekday() !== 6 && date.isoWeekday() !== 7)
remaining -= increment;
}
return date;
};
See Fiddle here: http://jsfiddle.net/dain/5xrr79h0/
Edit: now fixed issue adding 5 days to a day initially on a weekend
I know this question was posted long ago, but in case somebody bump on this, here is optimized solution using moment.js:
function getBusinessDays(startDate, endDate){
var startDateMoment = moment(startDate);
var endDateMoment = moment(endDate)
var days = Math.round(startDateMoment.diff(endDateMoment, 'days') - startDateMoment .diff(endDateMoment, 'days') / 7 * 2);
if (endDateMoment.day() === 6) {
days--;
}
if (startDateMoment.day() === 7) {
days--;
}
return days;
}
const calcBusinessDays = (d1, d2) => {
// Calc all days used including last day ( the +1 )
const days = d2.diff(d1, 'days') + 1;
console.log('Days:', days);
// how many full weekends occured in this time span
const weekends = Math.floor( days / 7 );
console.log('Full Weekends:', weekends);
// Subtract all the weekend days
let businessDays = days - ( weekends * 2);
// Special case for weeks less than 7
if( weekends === 0 ){
const cur = d1.clone();
for( let i =0; i < days; i++ ){
if( cur.day() === 0 || cur.day() === 6 ){
businessDays--;
}
cur.add(1, 'days')
}
} else {
// If the last day is a saturday we need to account for it
if (d2.day() === 6 ) {
console.log('Extra weekend day (Saturday)');
businessDays--;
}
// If the first day is a sunday we need to account for it
if (d1.day() === 0) {
console.log('Extra weekend day (Sunday)');
businessDays--;
}
}
console.log('Business days:', businessDays);
return businessDays;
}
This can be done without looping between all dates in between.
// get nb of weekend days
var startDateMonday = startDate.clone().startOf('isoWeek');
var endDateMonday = endDate.clone().startOf('isoWeek');
var nbWeekEndDays = 2 * endDateMonday.diff(startDateMonday, 'days') / 7;
var isoDayStart = startDate.isoWeekday();
if (isoDayStart > 5) // starts during the weekend
{
nbWeekEndDays -= (8 - isoDayStart);
}
var isoDayEnd = endDate.isoWeekday();
if (isoDayEnd > 5) // ends during the weekend
{
nbWeekEndDays += (8 - isoDayEnd);
}
// if we want to also exlcude holidays
var startOfStartDate = startDate.clone().startOf('day');
var nbHolidays = holidays.filter(h => {
return h.isSameOrAfter(startOfStartDate) && h.isSameOrBefore(endDate);
}).length;
var duration = moment.duration(endDate.diff(startDate));
duration = duration.subtract({ days: nbWeekEndDays + nbHolidays });
var nbWorkingDays = Math.floor(duration.asDays()); // get only nb of complete days
I am iterating from start date to end date and only counting days which are weekdays.
const calculateBusinessDays = (start_date, end_date) => {
const d1 = start_date.clone();
let num_days = 0;
while(end_date.diff(d1.add(1, 'days')) > 0) {
if ([0, 6].includes(d1.day())) {
// Don't count the days
} else {
num_days++;
}
}
return num_days;
}

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