Want to calculate date of birth from a given age - javascript

I'm trying to calculate the date of birth from a given age.
My logic is
When we enter an age say '5'. The date of birth will be calculated as exactly 5 years from the current date. Example current date is 20/8/2018.
Then date of birth will be 20/8/2013 if the age is 5.
So below is my code:
function validatedob() {
var dob_value = document.getElementById('dob').value;
var age_value = document.getElementById('age').value;
var current_date = new Date();
var birth_date = new Date();
var birth_year = current_date.getFullYear() - age_value;
var birth_month = current_date.getMonth();
var birth_day = current_date.getDate();
birth_date.setDate(current_date.getFullYear() - age_value);
birth_date.setMonth(current_date.getMonth());
birth_date.setFullYear(current_date.getDate());
document.getElementById('dob').setDate(birth_day);
document.getElementById('dob').setMonth(birth_month);
document.getElementById('dob').setFullYear(birth_year);
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
This is not working. I'm not goodwith html properties.
Can someone help me? how to achieve this?

Here is the simple answer:
> d1 = new Date(2018, 00, 01)
Date 2018-01-01T00:00:00.000Z
> d2 = new Date(d1.getFullYear() - 5, d1.getMonth(), d1.getDate())
Date 2013-01-01T00:00:00.000Z
But, I would suggest to use a library such as Luxon.
Date manipulation is an absolute nightmare if you do it by yourself. This video from Computerphile summarizes it better than I could:
https://www.youtube.com/watch?v=-5wpm-gesOY

Here is a really simple solution that works and some changes to your HTML.
Changes to HTML:
The div and label both had the id "age", this must be unique.
type="integer"doesn't exist, so i changed it to type="number".
And value="unknown"isn't the right format "yyy-MM-dd", so i just removed it.
for="DOB"to for="dob", now that works aswell
Code:
HTML
<div class="form-inline">
<label for="age">Age</label>
<input id="age" type="number" name="age"onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="dob">Date of Birth</label>
<input id="dob" type="date" name="date_of_birth" max="31-12-2030">
</div>
JavaScript
function validatedob() {
var age_value = document.getElementById("age").value;
var current_date = new Date();
var birth_date = new Date(current_date.getFullYear() - age_value, current_date.getMonth(), current_date.getDate() + 1);
document.getElementById("dob").valueAsDate = birth_date;
}

Here is some sample code for your reference
https://codepen.io/ji_in_coding/pen/wEvoMK
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth" >
<label for="DOB">Date of Birth</label>
<input id="dob" type="input" name="date_of_birth">
</div>
Javascript
function validatedob()
{
var age_value = document.getElementById("age").value;
var today = new Date();
var calculated_birthday = new Date(
parseInt(today.getFullYear())+parseInt(age_value),
today.getMonth(),
today.getDate());
document.getElementById("dob").value = calculated_birthday.toLocaleDateString("en-US");
}

You're issue is that you are trying to setDate and cie on a HTMLElement. The input dob expect a string formatted as yyyy-MM-dd. You can try something like that:
var $dob = document.getElementById('dob');
var $age = document.getElementById('age');
function validatedob() {
var age = $age.value;
var date = new Date();
date.setFullYear(date.getFullYear() - age);
$dob.value = formatDate(date);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
PS: For performance purpose avoid to repeat document.getElementById(...) in each method call. Do it once as done in my example.

Related

How to disable previous date using HTML5 datetime-local input?

I would simply like to prevent users from entering or disable the previous dates in input datetime-local , is there a way to do this?
Here is what I have done, unfortunately nothing happens on this code:
<input type="datetime-local" class="form-control col-md-6" name="book" required>
<script>
var today = new Date().toISOString().split('T')[0];
document.getElementsByName('book')[0].setAttribute('min', today);
</script>
try this
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("book")[0].min = today;
<input type="datetime-local" class="form-control col-md-6" name="book" required>
<div class="row">
<div class="col-md-6">
<label for="time_start">{{ __('adminstaticword.timestart') }}:<sup class="redstar">*</sup></label>
<input type="datetime-local" class="form-control" name="time_start" id="time_start" placeholder="Enter time_start" required min="{{date('Y-m-d')}}" value="{{ old('time_start') }}" >
<script>
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("time_start")[0].min = today;
</script>
</div>

How to set the year value in input date

I want to set just the year in my input date
var dateVal = $('#mydate').val();
new Date(dateVal).setFullYear(2015);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="mydate">My input</label>
<input id="mydate" type="date">
It's probably not the most effective one, but try this:
function clicked() {
alert(new Date(document.getElementById("year").value, 01, 01, 00, 00, 00, 00));
}
<input type="number" name="year" min="1000" max="9999" id="year">
<input type="button" onclick="clicked()" value="Click Me!">
This gives me a year right. You can change the min and max value of the text box.
Try below code, Here you can set the year value as required but you cannot show only year to date field as it will be invalid date and you cannot choose date format to show only year. You can show year in normal text input as shown below.
$(document).ready(function(){
var dateVal = $('#mydate').val();
var now;
if(dateVal) {
now = new Date(dateVal);
} else {
now = new Date();
}
now.setFullYear(2015);
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var myDate = now.getFullYear()+"-"+(month)+"-"+(day) ; // for full date
$('#mydate').val(myDate);
$('#myyear').val(now.getFullYear());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="mydate">My input</label>
<input id="mydate" type="date">
<input id="myyear" type="text">
You can do it like this. As only year is not supported in input type date i had taken another input field.
$('#mydate').change(function() {
var dateVal = $('#mydate').val();
console.log(dateVal);
getYear = dateVal.split('-');
$("#year").val(getYear[0]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="mydate">My input</label>
<input id="mydate" type="date">
<input id="year" type="text" disabled>

HTML How to set range of values for input depending on answer in another input

on my web form I have a question that asks for the date of birth and the gender.
I want to make a check using Javascript that makes sure that if the user selected "male" he has to be over 18 and under 55 years old. But if they selected "female" they have to be over 20 and under 50 years old.
(Sample of my HTML)I have:
<b>Gender: </b><br>
<input type="radio" name="Gender" value="male" required> Male
<input type="radio" name="Gender" value="female" required> Female
<br><br>
<b>Date of Birth: </b><br>
<input type="date" name="dob" required >
<br><br>
How do I do this?
Since there weren't any helpful answers, this is what I ended up doing myself:
function checkGender() {
var test = document.getElementById("male").checked;
document.getElementById("demo").innerHTML = test;
if (test == true) {
ageMin = 18;
ageMax = 55;
} else {
ageMin = 20;
ageMax = 50;
}
//The following are only used to test that the values work
document.getElementById("demo1").innerHTML = ageMin;
document.getElementById("demo2").innerHTML = ageMax;
var dateString = document.getElementById("doB").value;
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth()- birthDate.getMonth();
document.getElementById("demo3").innerHTML = dateString;
document.getElementById("demo4").innerHTML = today;
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
document.getElementById("demo5").innerHTML = age;
if (age<ageMin || age>ageMax) {
alert("Age is outside limits, please try again.");
stop();
}
}
HTML side of things:
<div class="form-row">
<br>
<legend class="col-form-label col-sm-1 col-sm-offset-1">Gender:</legend>
<div class="col-sm-4">
<div class="form-check">
<input class="form-check-input" id="male" type="radio"
name="Gender" value="male" required checked name="gender">
<label class="form-check-label" for="male">
Male
</label>
</div>
<div class="form-check">
<input id="female" type="radio" name="Gender" value="female" required name="gender">
<label class="form-check-label" for="female">
Female
</label>
</div>
</div>
<div class="col-sm-4">
<label for="doB">Date of Birth:</label><br>
<input id="doB" type="date" name="dob" required>
</div>
</div>
Modifying HTMLElement attributes
Basically, what you're looking for is, when you click on the radio button it triggers a function that then modifies the attribute min and changes the date
maleRadioButton.addEventListener('click', () => dateInput.setAttribute('min', new Date(new Date().setFullYear(new Date().getFullYear() - 18)).toLocaleDateString())
FYI, I sincerely hope that there the reason for using different age ranges for different genders is not sexist.

Could not diferentiate the date using the javascript [duplicate]

This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 4 years ago.
I am facing one problem. I am unable to differentiate the date difference using the javascript. I am explaining my code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log('date',date_diff <= 0);
Here I need enddate always should be greater than the start date. Here I am attaching my datetime code.
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
</div>
Here I am getting the date field value like this i.e-03-01-2018 02:46. I need always the end date time should be greater than the start date time but in my case in console message always I am getting the result false.
Try this:
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="17-07-2017" placeholder="17-06-2017"/>
</div>
</div>
</div>
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log(date_diff >= 0);
You just need to change the line: console.log('date',date_diff <= 0);
Simply do like this :
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var stdate = new Date(startdate_val).toISOString();
var enddate = new Date(enddate_val).toISOString();
//Then
Console.log(enddate >= stdate);
Sample Code that I've tried:
var startdate_val = '01-03-2018 02:45';
var enddate_val = '01-03-2018 02:45';
var stdate = new Date(startdate_val);
var enddate = new Date(enddate_val);
//Then
alert(enddate >= stdate);
Returns True
Fiddle
Converting the string to Date Object will be better than the manual labor.
in your HTML code, there is no value so you can't compare it to page load time, because it is blank.
somehow if you are using any click functionality then
please update your code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day = 1000 * 60 * 60 * 24;
var x = startdate_val.split("-");
var y = enddate_val.split("-");
var date1 = new Date(x[2], (x[1] - 1), x[0]);
var date2 = new Date(y[2], (y[1] - 1), y[0])
var month1 = x[1] - 1;
var month2 = y[1] - 1;
var date_diff = Math.ceil((date2.getTime() - date1.getTime()) / (one_day));
if (date_diff <= 0)
console.log(false);
else
console.log(true);
AND HTML FOR PAGE LOAD
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017" />
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="18-06-2017" placeholder="17-06-2017" />
</div>
</div>
</div>

How to set values for datepicker in jquery

I have a list of datepickers i need to set the value based on selection of first date picker, if we select the value in first date picker same value should be passed to all other date pickers
<input name="start" id='from' class="date-pick form-control" data-date-format="dd/mm/yyyy" type="text" />
<input name="start" id='to' class="date-pick form-control" data-date-format="dd/mm/yyyy" type="text" />
<input name="start" id='return' class="date-pick form-control" data-date-format="dd/mm/yyyy" type="text" />
<input name="start" id='depart' class="date-pick form-control" data-date-format="dd/mm/yyyy" type="text" />
Here is my jquery
$('input.date-pick, .input-daterange input[name="start"]').datepicker().on('changeDate', function (ev) {
var date2 = $('.date-pick').datepicker('getDate', '+1d');
//alert (date2);
date2.setDate(date2.getDate()+1);
$('input.date-pick).datepicker('setDate', date2);
});
But its not working.Please help to resolve this
Thanks in advance
$(function () {
$("#datepicker1, #datepicker2, #datepicker3, #datepicker4").datepicker();
$("#datepicker1").datepicker("option", "onSelect", function (dateText, inst) {
var date1 = $.datepicker.parseDate(inst.settings.dateFormat || $.datepicker._defaults.dateFormat, dateText, inst.settings);
var date2 = new Date(date1.getTime());
date2.setDate(date2.getDate() + 1);
$("#datepicker2").datepicker("setDate", date1);
var date3 = new Date(date1.getTime());
date3.setDate(date3.getDate() + 2);
$("#datepicker3").datepicker("setDate", date1);
var date4 = new Date(date1.getTime());
date4.setDate(date4.getDate() + 3);
$("#datepicker4").datepicker("setDate", date1);
});
});
Link Here.

Categories

Resources