I am developing a system which requires that you should be at least 18 years old to register.
For doing this validation i have implemented date difference in javascript in following way, but it is not accurate, is there any javascript function or other way to do this?
var d1=new Date(1985,1,28);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var years_old=milli/milliPerYear;
Legally being at least 18 years old is not about the amount of time corresponding to the average duration of 18 years (years aren't always the same length). It is about the current date being after your 18th birth date. Hence, you should just add 18 to the year count on the birthdate and see if this is before or after the present date, e.g.
var birthDate = new Date(1985,1,28);
var today = new Date();
if (today >= new Date(birthDate.getFullYear() + 18, birthDate.getMonth(), birthDate.getDate())) {
// Allow access
} else {
// Deny access
}
You should do the same validation on the server side as well.
Note that this also handles people born on 29th February the correct way: in this case JavaScript will create a date object to represent the 1st March 18 years later.
I like http://momentjs.com/
<script src="moment.min.js"></script>
<script>
var dob = new moment([1985,1,28]);
var age = new.moment().diff(dob, 'years')
if (age >= 18) {
...
}
</script>
Related
I am using moment.js. I want to restrict the user son that he can only select a date which is from current date to 50 years before.
In short, i just want that user's date of birth cannot be more than 50 years. So, from the current date, only ranges before the 50 years should only be there.
How can i do so? please guide me.
So you have to calculate 50 years back date first
https://momentjs.com/docs/#/manipulating/subtract/
fiftyYearsBackDate = moment().subtract(50, "years")
Get user Selected date
userDate = new Date()
Create moment object from that and do query
https://momentjs.com/docs/#/query/is-after/
moment(userDate).isAfter(fiftyYearsBackDate)
this will return boolean that you can use to show the error message.
You want to calculate the difference in years between now and the birthdate, and check if it's bigger than 50.
const birthDate = '1970-01-01'
const yearsDiff = moment().diff(birthDate, 'years');
If you want to get the difference of years in decimal:
const yearsDiff = moment().diff(birthDate, 'years', true);
The yearsDiff will contain the difference, so you can do an if check on it to see if it's bigger than 50.
Official docs for this: https://momentjs.com/docs/#/displaying/difference/
By using moment js you can easily get past and future dates like this -
const past = moment().subtract(50, 'years'); // To past
const future = moment().add(50, 'years'); // Back to future
Finally
const today = moment();
moment(today).isAfter(past, 'year'); // return: true || false
The reference site URL is - https://everyday.codes/javascript/how-to-format-date-in-javascript-with-moment-js/
Without moment.js you can test if the birthdate is less than today minus 50 years:
birthdate < new Date().setFullYear(new Date().getFullYear() - 50);
Example use:
let testDates = [
new Date(1970,0,1), // 1 Jan 1970
new Date(2000,0,1) // 1 Jan 2000
].forEach(date => console.log(
`More than 50 years ago?\n` +
`${date.toDateString()}: ${date < new Date().setFullYear(new Date().getFullYear() - 50)}`
));
The only behaviour to check is around 29 Feb. Some places move the birthday to 28 February in non–leap years and others to 1 March.
I have 3 seperate inputs, one for day, month and year. Only the year is required to show on page load, the user only needs to fill in the year first.
Currently I am able to check if someone is over 16 or under 16 by simply checking the year.
checkAge() {
let yearOfBirth = new Date().getFullYear() - this.form.dobYear;
if (yearOfBirth > 16) {
this.isSixteen = false;
this.belowSixteen = false;
}
}
When comparing the current year minus the user's input, if it equals to 16, then I have two select elements displaying the day and month, both of these will need to be filled in.
Here I need to compare the users input to see if the age is indeed 16, if they are a few months away from there 16th birthday for example then I want them to be seen as below 16, otherwise show them as 16 years of age.
I am using BootstrapVue and Vue.js also if it helps.
Get current Date
var base=new Date();
decrease it by 16 years
base.setFullYear(base.getFullYear()-16);
make a Date object from user input
var birthday=new Date(y,m,d);
compare the two
if(birthday.getTime()<=base.getTime())
// ok
else
// not ok
function check(event){
var base=new Date();
res.innerText="It is "+base;
base.setFullYear(base.getFullYear()-16);
res.innerText+="\n16 years ago it was "+base;
var bday=event.target.valueAsDate;
if(bday)
res.innerText+="\nVerdict: "+(bday.getTime()<base.getTime()?"Okay":"Too young");
}
Birthday: <input type="date" oninput="check(event)" value="0"><br>
<div id="res"></div>
To check only the year:
function calculateYearDiff(y){ // birthday year
return (new Date()).getUTCFullYear() - y;
}
^This will return difference in years between now and given year.
To check full birthday date:
function calculateAge(y,m,d){ // birthday year, month, day
var birthday = new Date(y + '-' + m + '-' + d);
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs);
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
^This will return full years between given birthday and now.
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);
This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks
I am trying to create a simple script that gives me the next recycling date based on a biweekly schedule starting on Wed Jul 6, 2011. So I've created this simple function...
function getNextDate(startDate) {
if (today <= startDate) {
return startDate;
}
// calculate the day since the start date.
var totalDays = Math.ceil((today.getTime()-startDate.getTime())/(one_day));
// check to see if this day falls on a recycle day
var bumpDays = totalDays%14; // mod 14 -- pickup up every 14 days...
// pickup is today
if (bumpDays == 0) {
return today;
}
// return the closest day which is in 14 days, less the # of days since the last
// pick up..
var ms = today.getTime() + ((14- bumpDays) * one_day);
return new Date(ms);
}
and can call it like...
var today=new Date();
var one_day=1000*60*60*24; // one day in milliseconds
var nextDate = getNextDate(new Date(2011,06,06));
so far so good... but when I project "today" to 10/27/2011, I get Tuesday 11/8/2011 as the next date instead of Wednesday 11/9/2011... In fact every day from now thru 10/26/2011 projects the correct pick-up... and every date from 10/27/2011 thru 2/28/2012 projects the Tuesday and not the Wednesday. And then every date from 2/29/2012 (leap year) thru 10/24/2012 (hmmm October again) projects the Wednesday correctly. What am I missing? Any help would be greatly appreciated..
V
The easiest way to do this is update the Date object using setDate. As the comments for this answer indicate this isn't officially part of the spec, but it is supported on all major browsers.
You should NEVER update a different Date object than the one you did the original getDate call on.
Sample implementation:
var incrementDate = function (date, amount) {
var tmpDate = new Date(date);
tmpDate.setDate(tmpDate.getDate() + amount)
return tmpDate;
};
If you're trying to increment a date, please use this function. It will accept both positive and negative values. It also guarantees that the used date objects isn't changed. This should prevent any error which can occur if you don't expect the update to change the value of the object.
Incorrect usage:
var startDate = new Date('2013-11-01T11:00:00');
var a = new Date();
a.setDate(startDate.getDate() + 14)
This will update the "date" value for startDate with 14 days based on the value of a. Because the value of a is not the same is the previously defined startDate it's possible to get a wrong value.
Expanding on Exellian's answer, if you want to calculate any period in the future (in my case, for the next pay date), you can do a simple loop:
var today = new Date();
var basePayDate = new Date(2012, 9, 23, 0, 0, 0, 0);
while (basePayDate < today) {
basePayDate.setDate(basePayDate.getDate()+14);
}
var nextPayDate = new Date(basePayDate.getTime());
basePayDate.setDate(nextPayDate.getDate()-14);
document.writeln("<p>Previous pay Date: " + basePayDate.toString());
document.writeln("<p>Current Date: " + today.toString());
document.writeln("<p>Next pay Date: " + nextPayDate.toString());
This won't hit odd problems, assuming the core date services work as expected. I have to admit, I didn't test it out to many years into the future...
Note: I had a similar issue; I wanted to create an array of dates on a weekly basis, ie., start date 10/23/2011 and go for 12 weeks. My code was more or less this:
var myDate = new Date(Date.parse(document.eventForm.startDate.value));
var toDate = new Date(myDate);
var week = 60 * 60 * 24 * 7 * 1000;
var milliseconds = toDate.getTime();
dateArray[0] = myDate.format('m/d/Y');
for (var count = 1; count < numberOccurrences; count++) {
milliseconds += week;
toDate.setTime(milliseconds);
dateArray[count] = toDate.format('m/d/Y');
}
Because I didn't specify the time and I live in the US, my default time was midnight, so when I crossed the daylight savings time border, I moved into the previous day. Yuck. I resolved it by setting my time of day to noon before I did my week calculation.