How to compare two Dates both Month and Year in Jquery - javascript

I have the following date picker fields in my view. I want to validate that fromDate must be less than todate.
#(Html.Kendo().DatePickerFor(m => m.FromDate)
.Format("{0:MM/yyyy}")
.Depth(CalendarView.Year)
.Start(CalendarView.Year)
)
And From Date
#(Html.Kendo().DatePickerFor(m => m.ToDate)
.Format("{0:MM/yyyy}")
.Depth(CalendarView.Year)
.Start(CalendarView.Year)
)
I used this Jquery but it only check the month Part. How can compare both the month and the year
function validateDateRange() {
var messageText = '';
var fromDate = $('#FromDate').val();
var toDate = $('#ToDate').val();
if ((fromDate > toDate) && (toDate != null || toDate.length != 0) && (fromDate != null || fromDate.length != 0)) {
messageText = 'start Date Must be greater than or equal to the end date.';
}
return messageText;
}

You can just change the date values into timestamp
function validateDateRange() {
var messageText = '';
var fromText = $('#FromDate').val();
var toText = $('#ToDate').val();
// since from/to texts has different date format we need to change it
// to a format new Date() would accept
var fromSplit = fromText.split("/");
var toSplit = toText.split("/");
// just put 1 day if it's not necessary
fromText = fromSplit[1] + "-" + fromSplit[0] + "-" + "1";
toText = toSplit[1] + "-" + toSplit[0] + "-" + "1";
// multiplying date by 1 will return a timestamp
var fromDate = new Date(fromText) * 1;
var toDate = new Date(toText) * 1;
/* Shouldn't be start date be lesser than end date? but whatever */
if (fromDate < toDate) {
messageText = 'start Date Must be greater than or equal to the end date.';
}
return messageText;
}

try Moment.js it has a lot for features, you can simply calculate like this.
var a = moment([2008, 9]);
var b = moment([2007, 0]);
a.diff(b, 'years'); // 1
a.diff(b, 'years', true); // 1.75
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Related

Calculate age with Javascript from Bootstrap datepicker [duplicate]

How can I calculate an age in years, given a birth date of format YYYYMMDD? Is it possible using the Date() function?
I am looking for a better solution than the one I am using now:
var dob = '19800810';
var year = Number(dob.substr(0, 4));
var month = Number(dob.substr(4, 2)) - 1;
var day = Number(dob.substr(6, 2));
var today = new Date();
var age = today.getFullYear() - year;
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
alert(age);
Try this.
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
I believe the only thing that looked crude on your code was the substr part.
Fiddle: http://jsfiddle.net/codeandcloud/n33RJ/
I would go for readability:
function _calculateAge(birthday) { // birthday is a date
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
Disclaimer: This also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).
Instead I would recommend using a library for this, if precision is very important. Also #Naveens post, is probably the most accurate, as it doesn't rely on the time of day.
Important: This answer doesn't provide an 100% accurate answer, it is off by around 10-20 hours depending on the date.
There are no better solutions ( not in these answers anyway ). - naveen
I of course couldn't resist the urge to take up the challenge and make a faster and shorter birthday calculator than the current accepted solution.
The main point for my solution, is that math is fast, so instead of using branching, and the date model javascript provides to calculate a solution we use the wonderful math
The answer looks like this, and runs ~65% faster than naveen's plus it's much shorter:
function calcAge(dateString) {
var birthday = +new Date(dateString);
return ~~((Date.now() - birthday) / (31557600000));
}
The magic number: 31557600000 is 24 * 3600 * 365.25 * 1000
Which is the length of a year, the length of a year is 365 days and 6 hours which is 0.25 day. In the end i floor the result which gives us the final age.
Here is the benchmarks: http://jsperf.com/birthday-calculation
To support OP's data format you can replace +new Date(dateString);
with +new Date(d.substr(0, 4), d.substr(4, 2)-1, d.substr(6, 2));
If you can come up with a better solution please share! :-)
Clean one-liner solution using ES6:
const getAge = birthDate => Math.floor((new Date() - new Date(birthDate).getTime()) / 3.15576e+10)
// today is 2018-06-13
getAge('1994-06-14') // 23
getAge('1994-06-13') // 24
I am using a year of 365.25 days (0.25 because of leap years) which are 3.15576e+10 milliseconds (365.25 * 24 * 60 * 60 * 1000) respectively.
It has a few hours margin so depending on the use case it may not be the best option.
With momentjs:
/* The difference, in years, between NOW and 2012-05-07 */
moment().diff(moment('20120507', 'YYYYMMDD'), 'years')
Some time ago I made a function with that purpose:
function getAge(birthDate) {
var now = new Date();
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
// days since the birthdate
var days = Math.floor((now.getTime() - birthDate.getTime())/1000/60/60/24);
var age = 0;
// iterate the years
for (var y = birthDate.getFullYear(); y <= now.getFullYear(); y++){
var daysInYear = isLeap(y) ? 366 : 365;
if (days >= daysInYear){
days -= daysInYear;
age++;
// increment the age only if there are available enough days for the year.
}
}
return age;
}
It takes a Date object as input, so you need to parse the 'YYYYMMDD' formatted date string:
var birthDateStr = '19840831',
parts = birthDateStr.match(/(\d{4})(\d{2})(\d{2})/),
dateObj = new Date(parts[1], parts[2]-1, parts[3]); // months 0-based!
getAge(dateObj); // 26
Here's my solution, just pass in a parseable date:
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
// ageMonth = age.getMonth(); // Accurate calculation of the month part of the age
// ageDay = age.getDate(); // Approximate calculation of the day part of the age
}
Alternate solution, because why not:
function calculateAgeInYears (date) {
var now = new Date();
var current_year = now.getFullYear();
var year_diff = current_year - date.getFullYear();
var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
var has_had_birthday_this_year = (now >= birthday_this_year);
return has_had_birthday_this_year
? year_diff
: year_diff - 1;
}
function age()
{
var birthdate = $j('#birthDate').val(); // in "mm/dd/yyyy" format
var senddate = $j('#expireDate').val(); // in "mm/dd/yyyy" format
var x = birthdate.split("/");
var y = senddate.split("/");
var bdays = x[1];
var bmonths = x[0];
var byear = x[2];
//alert(bdays);
var sdays = y[1];
var smonths = y[0];
var syear = y[2];
//alert(sdays);
if(sdays < bdays)
{
sdays = parseInt(sdays) + 30;
smonths = parseInt(smonths) - 1;
//alert(sdays);
var fdays = sdays - bdays;
//alert(fdays);
}
else{
var fdays = sdays - bdays;
}
if(smonths < bmonths)
{
smonths = parseInt(smonths) + 12;
syear = syear - 1;
var fmonths = smonths - bmonths;
}
else
{
var fmonths = smonths - bmonths;
}
var fyear = syear - byear;
document.getElementById('patientAge').value = fyear+' years '+fmonths+' months '+fdays+' days';
}
I think that could be simply like that:
function age(dateString){
let birth = new Date(dateString);
let now = new Date();
let beforeBirth = ((() => {birth.setDate(now.getDate());birth.setMonth(now.getMonth()); return birth.getTime()})() < birth.getTime()) ? 0 : 1;
return now.getFullYear() - birth.getFullYear() - beforeBirth;
}
age('09/20/1981');
//35
Works also with a timestamp
age(403501000000)
//34
That's the most elegant way for me:
const getAge = (birthDateString) => {
const today = new Date();
const birthDate = new Date(birthDateString);
const yearsDifference = today.getFullYear() - birthDate.getFullYear();
if (
today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())
) {
return yearsDifference - 1;
}
return yearsDifference;
};
console.log(getAge('2018-03-12'));
This question is over 10 years old an nobody has addressed the prompt that they already have the birth date in YYYYMMDD format?
If you have a past date and the current date both in YYYYMMDD format, you can very quickly calculate the number of years between them like this:
var pastDate = '20101030';
var currentDate = '20210622';
var years = Math.floor( ( currentDate - pastDate ) * 0.0001 );
// 10 (10.9592)
You can get the current date formatted as YYYYMMDD like this:
var now = new Date();
var currentDate = [
now.getFullYear(),
('0' + (now.getMonth() + 1) ).slice(-2),
('0' + now.getDate() ).slice(-2),
].join('');
To test whether the birthday already passed or not, I define a helper function Date.prototype.getDoY, which effectively returns the day number of the year. The rest is pretty self-explanatory.
Date.prototype.getDoY = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.floor(((this - onejan) / 86400000) + 1);
};
function getAge(birthDate) {
function isLeap(year) {
return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
}
var now = new Date(),
age = now.getFullYear() - birthDate.getFullYear(),
doyNow = now.getDoY(),
doyBirth = birthDate.getDoY();
// normalize day-of-year in leap years
if (isLeap(now.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyNow--;
if (isLeap(birthDate.getFullYear()) && doyNow > 58 && doyBirth > 59)
doyBirth--;
if (doyNow <= doyBirth)
age--; // birthday not yet passed this year, so -1
return age;
};
var myBirth = new Date(2001, 6, 4);
console.log(getAge(myBirth));
I just had to write this function for myself - the accepted answer is fairly good but IMO could use some cleanup. This takes a unix timestamp for dob because that was my requirement but could be quickly adapted to use a string:
var getAge = function(dob) {
var measureDays = function(dateObj) {
return 31*dateObj.getMonth()+dateObj.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - (measureDays(now) < measureDays(d));
}
Notice I've used a flat value of 31 in my measureDays function. All the calculation cares about is that the "day-of-year" be a monotonically increasing measure of the timestamp.
If using a javascript timestamp or string, obviously you'll want to remove the factor of 1000.
function getAge(dateString) {
var dates = dateString.split("-");
var d = new Date();
var userday = dates[0];
var usermonth = dates[1];
var useryear = dates[2];
var curday = d.getDate();
var curmonth = d.getMonth()+1;
var curyear = d.getFullYear();
var age = curyear - useryear;
if((curmonth < usermonth) || ( (curmonth == usermonth) && curday < userday )){
age--;
}
return age;
}
To get the age when european date has entered:
getAge('16-03-1989')
I've checked the examples showed before and they didn't worked in all cases, and because of this i made a script of my own. I tested this, and it works perfectly.
function getAge(birth) {
var today = new Date();
var curr_date = today.getDate();
var curr_month = today.getMonth() + 1;
var curr_year = today.getFullYear();
var pieces = birth.split('/');
var birth_date = pieces[0];
var birth_month = pieces[1];
var birth_year = pieces[2];
if (curr_month == birth_month && curr_date >= birth_date) return parseInt(curr_year-birth_year);
if (curr_month == birth_month && curr_date < birth_date) return parseInt(curr_year-birth_year-1);
if (curr_month > birth_month) return parseInt(curr_year-birth_year);
if (curr_month < birth_month) return parseInt(curr_year-birth_year-1);
}
var age = getAge('18/01/2011');
alert(age);
Get the age (years, months and days) from the date of birth with javascript
Function calcularEdad (years, months and days)
function calcularEdad(fecha) {
// Si la fecha es correcta, calculamos la edad
if (typeof fecha != "string" && fecha && esNumero(fecha.getTime())) {
fecha = formatDate(fecha, "yyyy-MM-dd");
}
var values = fecha.split("-");
var dia = values[2];
var mes = values[1];
var ano = values[0];
// cogemos los valores actuales
var fecha_hoy = new Date();
var ahora_ano = fecha_hoy.getYear();
var ahora_mes = fecha_hoy.getMonth() + 1;
var ahora_dia = fecha_hoy.getDate();
// realizamos el calculo
var edad = (ahora_ano + 1900) - ano;
if (ahora_mes < mes) {
edad--;
}
if ((mes == ahora_mes) && (ahora_dia < dia)) {
edad--;
}
if (edad > 1900) {
edad -= 1900;
}
// calculamos los meses
var meses = 0;
if (ahora_mes > mes && dia > ahora_dia)
meses = ahora_mes - mes - 1;
else if (ahora_mes > mes)
meses = ahora_mes - mes
if (ahora_mes < mes && dia < ahora_dia)
meses = 12 - (mes - ahora_mes);
else if (ahora_mes < mes)
meses = 12 - (mes - ahora_mes + 1);
if (ahora_mes == mes && dia > ahora_dia)
meses = 11;
// calculamos los dias
var dias = 0;
if (ahora_dia > dia)
dias = ahora_dia - dia;
if (ahora_dia < dia) {
ultimoDiaMes = new Date(ahora_ano, ahora_mes - 1, 0);
dias = ultimoDiaMes.getDate() - (dia - ahora_dia);
}
return edad + " años, " + meses + " meses y " + dias + " días";
}
Function esNumero
function esNumero(strNumber) {
if (strNumber == null) return false;
if (strNumber == undefined) return false;
if (typeof strNumber === "number" && !isNaN(strNumber)) return true;
if (strNumber == "") return false;
if (strNumber === "") return false;
var psInt, psFloat;
psInt = parseInt(strNumber);
psFloat = parseFloat(strNumber);
return !isNaN(strNumber) && !isNaN(psFloat);
}
One more possible solution with moment.js:
var moment = require('moment');
var startDate = new Date();
var endDate = new Date();
endDate.setDate(endDate.getFullYear() + 5); // Add 5 years to second date
console.log(moment.duration(endDate - startDate).years()); // This should returns 5
I am a bit too late but I found this to be the simplest way to calculate a birth date.
Hopefully this will help.
function init() {
writeYears("myage", 0, Age());
}
function Age() {
var birthday = new Date(1997, 02, 01), //Year, month-1 , day.
today = new Date(),
one_year = 1000 * 60 * 60 * 24 * 365;
return Math.floor((today.getTime() - birthday.getTime()) / one_year);
}
function writeYears(id, current, maximum) {
document.getElementById(id).innerHTML = current;
if (current < maximum) {
setTimeout(function() {
writeYears(id, ++current, maximum);
}, Math.sin(current / maximum) * 200);
}
}
init()
<span id="myage"></span>
Works perfect for me, guys.
getAge(birthday) {
const millis = Date.now() - Date.parse(birthday);
return new Date(millis).getFullYear() - 1970;
}
I know this is a very old thread but I wanted to put in this implementation that I wrote for finding the age which I believe is much more accurate.
var getAge = function(year,month,date){
var today = new Date();
var dob = new Date();
dob.setFullYear(year);
dob.setMonth(month-1);
dob.setDate(date);
var timeDiff = today.valueOf() - dob.valueOf();
var milliInDay = 24*60*60*1000;
var noOfDays = timeDiff / milliInDay;
var daysInYear = 365.242;
return ( noOfDays / daysInYear ) ;
}
Ofcourse you could adapt this to fit in other formats of getting the parameters. Hope this helps someone looking for a better solution.
I used this approach using logic instead of math.
It's precise and quick.
The parameters are the year, month and day of the person's birthday.
It returns the person's age as an integer.
function calculateAge(year, month, day) {
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getUTCMonth() + 1;
var currentDay = currentDate.getUTCDate();
// You need to treat the cases where the year, month or day hasn't arrived yet.
var age = currentYear - year;
if (currentMonth > month) {
return age;
} else {
if (currentDay >= day) {
return age;
} else {
age--;
return age;
}
}
}
Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.
I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.
/**
* Calculates human age in years given a birth day. Optionally ageAtDate
* can be provided to calculate age at a specific date
*
* #param string|Date Object birthDate
* #param string|Date Object ageAtDate optional
* #returns integer Age between birthday and a given date or today
*/
function gregorianAge(birthDate, ageAtDate) {
// convert birthDate to date object if already not
if (Object.prototype.toString.call(birthDate) !== '[object Date]')
birthDate = new Date(birthDate);
// use today's date if ageAtDate is not provided
if (typeof ageAtDate == "undefined")
ageAtDate = new Date();
// convert ageAtDate to date object if already not
else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')
ageAtDate = new Date(ageAtDate);
// if conversion to date object fails return null
if (ageAtDate == null || birthDate == null)
return null;
var _m = ageAtDate.getMonth() - birthDate.getMonth();
// answer: ageAt year minus birth year less one (1) if month and day of
// ageAt year is before month and day of birth year
return (ageAtDate.getFullYear()) - birthDate.getFullYear()
- ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)
}
// Below is for the attached snippet
function showAge() {
$('#age').text(gregorianAge($('#dob').val()))
}
$(function() {
$(".datepicker").datepicker();
showAge();
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
DOB:
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
I've did some updated to one previous answer.
var calculateAge = function(dob) {
var days = function(date) {
return 31*date.getMonth() + date.getDate();
},
d = new Date(dob*1000),
now = new Date();
return now.getFullYear() - d.getFullYear() - ( measureDays(now) < measureDays(d));
}
I hope that helps :D
here is a simple way of calculating age:
//dob date dd/mm/yy
var d = 01/01/1990
//today
//date today string format
var today = new Date(); // i.e wed 04 may 2016 15:12:09 GMT
//todays year
var todayYear = today.getFullYear();
// today month
var todayMonth = today.getMonth();
//today date
var todayDate = today.getDate();
//dob
//dob parsed as date format
var dob = new Date(d);
// dob year
var dobYear = dob.getFullYear();
// dob month
var dobMonth = dob.getMonth();
//dob date
var dobDate = dob.getDate();
var yearsDiff = todayYear - dobYear ;
var age;
if ( todayMonth < dobMonth )
{
age = yearsDiff - 1;
}
else if ( todayMonth > dobMonth )
{
age = yearsDiff ;
}
else //if today month = dob month
{ if ( todayDate < dobDate )
{
age = yearsDiff - 1;
}
else
{
age = yearsDiff;
}
}
var now = DateTime.Now;
var age = DateTime.Now.Year - dob.Year;
if (now.Month < dob.Month || now.Month == dob.Month && now.Day < dob.Day) age--;
You may use this for age restriction in your form -
function dobvalidator(birthDateString){
strs = birthDateString.split("-");
var dd = strs[0];
var mm = strs[1];
var yy = strs[2];
var d = new Date();
var ds = d.getDate();
var ms = d.getMonth();
var ys = d.getFullYear();
var accepted_age = 18;
var days = ((accepted_age * 12) * 30) + (ms * 30) + ds;
var age = (((ys - yy) * 12) * 30) + ((12 - mm) * 30) + parseInt(30 - dd);
if((days - age) <= '0'){
console.log((days - age));
alert('You are at-least ' + accepted_age);
}else{
console.log((days - age));
alert('You are not at-least ' + accepted_age);
}
}
This is my modification:
function calculate_age(date) {
var today = new Date();
var today_month = today.getMonth() + 1; //STRANGE NUMBERING //January is 0!
var age = today.getYear() - date.getYear();
if ((today_month > date.getMonth() || ((today_month == date.getMonth()) && (today.getDate() < date.getDate())))) {
age--;
}
return age;
};
I believe that sometimes the readability is more important in this case. Unless we are validating 1000s of fields, this should be accurate and fast enough:
function is18orOlder(dateString) {
const dob = new Date(dateString);
const dobPlus18 = new Date(dob.getFullYear() + 18, dob.getMonth(), dob.getDate());
return dobPlus18 .valueOf() <= Date.now();
}
// Testing:
console.log(is18orOlder('01/01/1910')); // true
console.log(is18orOlder('01/01/2050')); // false
// When I'm posting this on 10/02/2020, so:
console.log(is18orOlder('10/08/2002')); // true
console.log(is18orOlder('10/19/2002')) // false
I like this approach instead of using a constant for how many ms are in a year, and later messing with the leap years, etc. Just letting the built-in Date to do the job.
Update, posting this snippet since one may found it useful. Since I'm enforcing a mask on the input field, to have the format of mm/dd/yyyy and already validating if the date is valid, in my case, this works too to validate 18+ years:
function is18orOlder(dateString) {
const [month, date, year] = value.split('/');
return new Date(+year + 13, +month, +date).valueOf() <= Date.now();
}

Pick a date then convert format from UNIX to UTC in yyyymmdd

Objective: Setup the date in the array at the end of the block to read: yyyymmdd including the zeros. (example data build: numDaysAPITimes = [20150403]). What I got is not getting the month correctly and the numDaysAPITimes array is storing only the year for some reason.
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date(backDateEpochTime); //Convert to UTC
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
numDaysAPITimes[i] = (curr_year + curr_month + curr_date);
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
a couple things:
your date info is getting added together as numbers, that why it seems the year is only going through. One way to handle that would be to use the toString() method.
you'll probably want leading zeroes on the day and month, which you can achieve by prepending a 0 and then doing a slice -2.
That would looks like This JSFiddle, or:
var totalPrecipSinceDate;
var numDaysAPITimes = [];
var userDataDatePick = 2;//document.getElementById('dateRngPick').value;
if (userDataDatePick >=1)
{
for (var i = 0; i <= (userDataDatePick-1); i++) //place user userData-1 where i <= input
{
var myDate = new Date(); //http://stackoverflow.com/questions/7693170/javascript-convert-from-epoch-string-to-date-object
var epoch = myDate.getTime();
var unixEpoch = Math.round(epoch/1000)
var backDateEpochTime = Math.round(unixEpoch - (86400 * i)); //Get each day (UNIX seconds)
var d = new Date((1000*backDateEpochTime)); //Convert to UTC
var curr_date = ("0" + d.getDate()).slice(-2)
var curr_month = ("0"+ (d.getMonth() + 1)).slice(-2); //Months are zero based
var curr_year = d.getFullYear();
console.log(d.getMonth());
numDaysAPITimes[i] = (curr_year.toString() + curr_month.toString() + curr_date.toString());
}
}
else
{
alert("You have not entered a valid number for the date.");
numDaysAPITimes.length = 0;
}
console.log(numDaysAPITimes)

Delivery Date Javascript Adapt To Exclude Weekends

I have been currently using this script
<script type="text/javascript">
var _next = new Date(new Date() * 1 + 24*60*60*1000*9);
document.write(" Your expected delivery date is " + (_next.getMonth() + 1) + "/" + _next.getDate() + "/" + _next.getFullYear());
</script>
I'm wondering how do I get it to exclude weekends if possible.
Just add hours if you like. this is a code that expects to deliver the next working day.
function myFunction() {
var d = new Date();
var weekday = new Array(7);
weekday[0] = "sunday";
weekday[1] = "monday";
weekday[2] = "tuesday";
weekday[3] = "wednesday";
weekday[4] = "thursday";
weekday[5] = "friday";
weekday[6] = "saturday";
var monthday = new Array(12);
monthday[0] = "01";
monthday[1] = "02";
monthday[2] = "03";
monthday[3] = "04";
monthday[4] = "05";
monthday[5] = "06";
monthday[6] = "07";
monthday[7] = "08";
monthday[8] = "09";
monthday[9] = "10";
monthday[10] = "11";
monthday[11] = "12";
if (d.getDay() > 0 && d.getDay() <= 4) {
d.setHours(d.getHours() + 24);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else if (d.getDay() == 0) {
d.setHours(d.getHours() + 48);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
} else {
d.setHours(d.getHours() + 72);
var deliver = weekday[d.getDay()];
var day = d.getDate();
var month = monthday[d.getMonth()];
var year = d .getFullYear();
document.getElementById("deliveryday").innerHTML = deliver + ' ' + day + '-' + month + '-' + year;
}
}
myFunction()
<script type="text/javascript">
<!--
var myDate=new Date();
if ( myDate.getHours() < 12 ) // less than 12pm
{
var daystodeliver = [7,5,5,5,5,8,7][myDate.getDay()];
}
else
{
var daystodeliver = [7,7,7,7,7,9,8][myDate.getDay()];
}
myDate.setDate(myDate.getDate()+daystodeliver);
document.write(['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'] [myDate.getDay()]);
var dayofmonth = myDate.getDate();
suffix = ((dayofmonth < 10)||(dayofmonth > 20)) ? ['th','st','nd','rd','th','th','th','th','th','th'][dayofmonth % 10] : 'th';
document.write(' ' + dayofmonth + suffix + ' ');
document.write(['January','February','March','April','May','June','July','August','Septembe r','October','November','December'][myDate.getMonth()]);
// -->
Try this:
function deliver(inDays, startingOn){
var s, f = 0, d;
if(!inDays)inDays = 0;
s = !startingOn ? new Date : new Date(startingOn);
for(var i=0,n,t=0,l=inDays; i<l; i++,t+=86400000){
n = new Date(s.getTime()+t).getDay();
if(n === 0 || n === 6)f++;
}
d = new Date(s.getTime()+86400000*(inDays+f));
return 'Your expected delivery date is '+d.toLocaleDateString();
}
// same day delivery
console.log(deliver());
// deliver in 9 days stating today
console.log(deliver(9));
// deliver in 9 days starting on October 12, 2013 - must be a valid Date String
console.log(deliver(9, 'October 12, 2013'));
/* Note that in the last example the Date starts on the weekend, therefore same
day becomes Monday, which if you don't work weekends is the first day you
would see the order anyways.
*/
This is good to show your Client when something is delivered. Make sure you set the actual date it your database, according to where you are, using a Server Side language like PHP.
You should pay me for this since it will work even on a leap year. Ha!
Try this to get the date
I wrote a routine that you supply a date object, apply the menthod, the public holidays in a separate list is passed and any holidays / public holidays including weekends are skipped over.
Its this post
// array of ISO YYYY-MM-DD format dates
publicHolidays = {
uk:["2020-01-01","2020-04-10","2020-04-13","2020-05-08","2020-05-25",
"2020-08-03","2020-08-31","2020-12-25","2020-12-28"],
usa:["2020-01-01","2020-01-20","2020-02-14","2020-02-17","2020-04-10",
"2020-04-12","2020-05-10","2020-05-25","2020-06-21","2020-07-03",
"2020-07-04","2020-09-07","2020-10-12","2020-10-31","2020,11,11",
"2020-11-26","2020-12-25"]
}
// check if there is a match in the array
Date.prototype.isPublicHoliday = function( data ){// we check for a public holiday
if(!data) return 1;
return data.indexOf(this.toISOString().slice(0,10))>-1? 0:1;
}
// calculation of business days
Date.prototype.businessDays = function( d, holidays ){
var holidays = holidays || false, t = new Date( this ); // copy date.
while( d ){ // we loop while d is not zero...
t.setDate( t.getDate() + 1 ); // set a date and test it
switch( t.getDay() ){ // switch is used to allow easier addition of other days of the week
case 0: case 6: break;// sunday & saturday
default: // check if we are a public holiday or not
d -= t.isPublicHoliday( holidays );
}
}
return t.toISOString().slice(0,10); // just the YYY-MM-DD
}
// dummy var, could be a form field input
OrderDate = "2020-02-12";
// test with a UK holiday date
var deliveryDate = new Date(OrderDate).businessDays(7, publicHolidays.usa);
// expected output 2020-02-25
console.log("Order date: %s, Delivery date: %s",OrderDate,deliveryDate );

Check if one date is between two dates

I need to check if a date - a string in dd/mm/yyyy format -
falls between two other dates having the same format dd/mm/yyyy
I tried this, but it doesn't work:
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var from = Date.parse(dateFrom);
var to = Date.parse(dateTo);
var check = Date.parse(dateCheck );
if((check <= to && check >= from))
alert("date contained");
I used debugger and checked, the to and from variables have isNaN value.
Could you help me?
Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
console.log(check > from && check < to)
Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.
Something like
if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime())) alert("date contained");
Try what's below. It will help you...
Fiddle : http://jsfiddle.net/RYh7U/146/
Script :
if(dateCheck("02/05/2013","02/09/2013","02/07/2013"))
alert("Availed");
else
alert("Not Availed");
function dateCheck(from,to,check) {
var fDate,lDate,cDate;
fDate = Date.parse(from);
lDate = Date.parse(to);
cDate = Date.parse(check);
if((cDate <= lDate && cDate >= fDate)) {
return true;
}
return false;
}
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Simplified way of doing this based on the accepted answer.
In my case I needed to check if current date (Today) is pithing the range of two other dates so used newDate() instead of hardcoded values but you can get the point how you can use hardcoded dates.
var currentDate = new Date().toJSON().slice(0,10);
var from = new Date('2020/01/01');
var to = new Date('2020/01/31');
var check = new Date(currentDate);
console.log(check > from && check < to);
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Here is a Date Prototype method written in typescript:
Date.prototype.isBetween = isBetween;
interface Date { isBetween: typeof isBetween }
function isBetween(minDate: Date, maxDate: Date): boolean {
if (!this.getTime) throw new Error('isBetween() was called on a non Date object');
return !minDate ? true : this.getTime() >= minDate.getTime()
&& !maxDate ? true : this.getTime() <= maxDate.getTime();
};
I did the same thing that #Diode, the first answer, but i made the condition with a range of dates, i hope this example going to be useful for someone
e.g (the same code to example with array of dates)
var dateFrom = "02/06/2013";
var dateTo = "02/09/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var dates= ["02/06/2013", "02/07/2013", "02/08/2013", "02/09/2013", "02/07/2013", "02/10/2013", "02/011/2013"];
dates.forEach(element => {
let parts = element.split("/");
let date= new Date(parts[2], parseInt(parts[1]) - 1, parts[0]);
if (date >= from && date < to) {
console.log('dates in range', date);
}
})
Try this:
HTML
<div id="eventCheck"></div>
JAVASCRIPT
// ----------------------------------------------------//
// Todays date
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
// Add Zero if it number is between 0-9
if(dd<10) {
dd = '0'+dd;
}
if(mm<10) {
mm = '0'+mm;
}
var today = yyyy + '' + mm + '' + dd ;
// ----------------------------------------------------//
// Day of event
var endDay = 15; // day 15
var endMonth = 01; // month 01 (January)
var endYear = 2017; // year 2017
// Add Zero if it number is between 0-9
if(endDay<10) {
endDay = '0'+endDay;
}
if(endMonth<10) {
endMonth = '0'+endMonth;
}
// eventDay - date of the event
var eventDay = endYear + '/' + endMonth + '/' + endDay;
// ----------------------------------------------------//
// ----------------------------------------------------//
// check if eventDay has been or not
if ( eventDay < today ) {
document.getElementById('eventCheck').innerHTML += 'Date has passed (event is over)'; // true
} else {
document.getElementById('eventCheck').innerHTML += 'Date has not passed (upcoming event)'; // false
}
Fiddle:
https://jsfiddle.net/zm75cq2a/
Suppose for example your date is coming like this & you need to install momentjs for advance date features.
let cmpDate = Thu Aug 27 2020 00:00:00 GMT+0530 (India Standard Time)
let format = "MM/DD/YYYY";
let startDate: any = moment().format(format);
let endDate: any = moment().add(30, "days").format(format);
let compareDate: any = moment(cmpDate).format(format);
var startDate1 = startDate.split("/");
var startDate2 = endDate.split("/");
var compareDate1 = compareDate.split("/");
var fromDate = new Date(startDate1[2], parseInt(startDate1[1]) - 1, startDate1[0]);
var toDate = new Date(startDate2[2], parseInt(startDate2[1]) - 1, startDate2[0]);
var checkDate = new Date(compareDate1[2], parseInt(compareDate1[1]) - 1, compareDate1[0]);
if (checkDate > fromDate && checkDate < toDate) {
... condition works between current date to next 30 days
}
This may feel a bit more intuitive. The parameter is just a valid date string.
This function returns true if the date passed as argument is in the current week, or false if not.
function isInThisWeek(dateToCheck){
// Create a brand new Date instance
const WEEK = new Date()
// create a date instance with the function parameter
//(format should be like dd/mm/yyyy or any javascript valid date format )
const DATEREF = new Date(dateToCheck)
// If the parameter is a not a valid date, return false
if(DATEREF instanceof Date && isNaN(DATEREF)){
console.log("invalid date format")
return false}
// Get separated date infos (the date of today, the current month and the current year) based on the date given as parameter
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]
// get Monday date by substracting the day index (number) in the week from the day value (count)
//in the month (like october 15th - 5 (-> saturday index)) and +1 because
//JS weirdly starts the week on sundays
const monday = (WEEK.getDate() - WEEK.getDay()) + 1
// get Saturday date
const sunday = monday + 6
// Start verification
if (yearR !== WEEK.getFullYear()) { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}
}
Try this
var gdate='01-05-2014';
date =Date.parse(gdate.split('-')[1]+'-'+gdate.split('-')[0]+'-'+gdate.split('-')[2]);
if(parseInt(date) < parseInt(Date.now()))
{
alert('small');
}else{
alert('big');
}
Fiddle
This question is very generic, hence people who are using date libraries also check for the answer, but I couldn't find any answer for the date libraries, hence I am posting the answer for Luxon users.
const fromDate = '2022-06-01T00:00:00.000Z';
const toDate = '2022-06-30T23:59:59.999Z';
const inputDate = '2022-08-09T20:26:13.380Z';
if (
DateTime.fromISO(inputDate) >= DateTime.fromISO(fromDate) &&
DateTime.fromISO(inputDate) <= DateTime.fromISO(toDate)
) {
console.log('within range');
} else {
console.log('not in range');
}

javascript check end date is greater than or equal to start date

Is it possible to check whether an end date is greater than or equal to a start date in Javascript? My dates are strings in the format 'dd/mm/yyyy'.
try this
var startDate = "05/01/2011";
var endDate = "09/01/2011";
var regExp = /(\d{1,2})\/(\d{1,2})\/(\d{2,4})/;
if(parseInt(endDate.replace(regExp, "$3$2$1")) > parseInt(startDate.replace(regExp, "$3$2$1"))){
alert("greater");
}
If the string format ('dd/mm/yyyy') doesn't change, this function should work:
function endAfterStart(start,end){
return new Date(start.split('/').reverse().join('/')) <
new Date(end.split('/').reverse().join('/'));
}
alert(endAfterStart('05/01/2011','09/01/2011')); //=> true
Or extend the Date.prototype:
Date.prototype.isBefore = Date.prototype.isBefore || function(dat){
return this < dat;
}
new Date('05/01/2011'.split('/').reverse().join('/'))
.before( new Date('09/01/2011'.split('/').reverse().join('/')) ); //=>true
Most simple way to do this.
function endAfterStart(start, end) {
var startDate = new Date(start);
var endDate = new Date(end);
return endDate.getTime() >= startDate.getTime();
}
function isDate(value)
{
var fromDate = document.getElementById("fromDate").value
var toDate= document.getElementById("toDate").value
//var curr_Date= new SimpleDateFormat("dd/mm/yyyy");
var dateRegEx = null;
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if (dateRegEx.test(fromDate)){
}
else{
alert("Invalid from date");
return false;
}
dateRegEx = new RegExp(/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/g);
if(dateRegEx.test(toDate)) {
}
else{
alert("Invalid to date");
return false;
}
var stDate = new Date(fromDate);
var enDate = new Date(toDate);
var compDate = enDate - stDate;
//var fdate=enDate-curr_Date;
if(compDate >= 0)
return true;
else
{
alert("To Date cannot be smaller than From Date");
return false;
}
/**/
}
This will work for Leap years also..in dd/mm/yyyy format(not any other format).
Took me some time to find, but JQuery implements this exact functionality with DatePicker date-range. (Source code available in link as well.)
Moment.js also handles date comparisons very well using the diff function.
check out this function
function CompareDates()
{
var str1 = document.getElementById("Fromdate").value;
var str2 = document.getElementById("Todate").value;
var dt1 = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1 = parseInt(str1.substring(6,10),10);
var dt2 = parseInt(str2.substring(0,2),10);
var mon2 = parseInt(str2.substring(3,5),10);
var yr2 = parseInt(str2.substring(6,10),10);
var date1 = new Date(yr1, mon1, dt1);
var date2 = new Date(yr2, mon2, dt2);
if(date2 < date1)
{
alert("To date cannot be greater than from date");
return false;
}
else
{
alert("Submitting ...");
document.form1.submit();
}
}
Try this,
function isDateCompare(){
var leadDate = document.getElementById('strDate').value;
var closeDate = document.getElementById('strDateClosed').value;
var date1 = new Date();
date1.setFullYear(leadDate.substr(6,4),(leadDate.substr(3,2)-1),leadDate.substr(0,2));
var date2 = new Date();
date2.setFullYear(closeDate.substr(6,4),(closeDate.substr(3,2)-1),closeDate.substr(0,2));
if (date1> date2)
{
alert("Expected Closed date cannot be less than Lead date.");
return false;
}
else
{
alert("true");
return false;
}
}
First use this function will convert string to Date type in js:
function common_getDateFromUI(str) {
var arr = str.split("/");
var returnDate = new Date(arr[2], arr[1] - 1, arr[0], 0, 0, 0, 0);
return returnDate;
}
Second: after you get the javascript date type, you just compare it as normal type like date1 > date2 or date1 == date2.
Or use this function to get the difference date between date:
function CalendarDays(startDate, endDate) {
if (endDate < startDate)
return 0;
// Calculate days between dates
var millisecondsPerDay = 86400 * 1000; // Day in milliseconds
startDate.setHours(0, 0, 0, 1); // Start just after midnight
endDate.setHours(23, 59, 59, 999); // End just before midnight
var diff = endDate - startDate; // Milliseconds between datetime objects
var days = Math.round(diff / millisecondsPerDay);
return days;
}
Follow this link is a simple demo to get difference days between dates. Link demo here
if (iForm.DiddfromDate.value == "")
{
alert(" Please enter a value");
iForm.DiddfromDate.focus();
return false;
}
if (iForm.DiddtoDate.value == "")
{
alert(" Please enter a value");
iForm.DiddtoDate.focus();
return false;
}
try {
var d1 = iForm.DiddfromDate.value.substr(0, 2);
var m1 = iForm.DiddfromDate.value.substr(3, 2);
var y1 = iForm.DiddfromDate.value.substr(6, 4);
var StrDate = m1 + "/" + d1 + "/" + y1;
var d2 = iForm.DiddtoDate.value.substr(0, 2);
var m2 = iForm.DiddtoDate.value.substr(3, 2);
var y2 = iForm.DiddtoDate.value.substr(6, 4);
var EndDate = m2 + "/" + d2 + "/" + y2;
var startDate = new Date(StrDate);
var endDate = new Date(EndDate);
if (startDate > endDate) {
alert('To date should be greater than From date.');
iForm.DiddfromDate.value = '';
iForm.DiddtoDate.value = '';
iForm.DiddfromDate.focus();
return false;
}
} catch (e) { alert(e.Description); }
return true;
Just convert the string to date and use getTime method of Date object to compare it.
Example code
var startDate = '04/04/2015'; //date in dd/mm/yyyy format
var endDate = '05/04/2015';
function compareDates(sDate, eDate) {
var dateTime1 = new Date(sDate).getTime(),
dateTime2 = new Date(eDate).getTime();
var diff = dateTime2 - dateTime1;
if (diff > 0) {
alert("endDate is greater than startDate");
return true;
}
}
compareDates(startDate, endDate);
Working Fiddle

Categories

Resources