extract year from date and calculate datedifference - javascript

I am relative new in coding and recently i have to do some date manipulations with data entered in a form. I searched a lot and I haven't found the solution that works for me.
Here is the issue:
The user enters following data in datetime-local fields in HTML:
1) Year of entering College (date 1)
2) Year of graduation (date 2)
3) Birthday (date 3)
I need a JQuery or a JavaScript script that uses this dates and output following:
1) Year of admitting, based on the admittion date (I know there is a getFullYear function, but I couldn't use it right...) >>> result1
2) Age at graduation (date difference between Birthdate and date of Graduation. >>> result2
I tried with adding datepicker but somehow I got really awful looking calendar which was displayed over the boxes. I couldn't install datetimepicker...
Thank you in advance. Your help is appreciated.
Here is my HTML code.
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />

You didn't include the js code which is more important for this question. I'll include a couple functions that should help.
To find a year from a date, I use the following function
function getYearFromDate(date){
const yearFromDate = new Date();
yearFromDate.setTime(date.getTime());
yearFromDate.setFullYear(date.getFullYear() + 1);
return yearFromDate;
}
console.log(getYearFromDate(new Date()));
And the graduation age copied mostly from Calculate age given the birth date in the format YYYYMMDD
function getYearsBetween(oldDate, newDate) {
var age = newDate.getFullYear() - oldDate.getFullYear();
var m = newDate.getMonth() - oldDate.getMonth();
if (m < 0 || (m === 0 && newDate.getDate() < oldDate.getDate())) {
age--;
}
return age;
}
Including moment.js is also an option, but it's a large library I like to avoid if I can.
EDIT I thought you wanted year + 1 day. Getting the full year from the date is even easier.
const date = new Date();
console.log(date.getFullYear());
Edit: All together now
function updateGradYear(event) {
console.log(event.target.value);
let date = new Date(event.target.value);
document.querySelector('#result1').value = date.getFullYear();
}
function updateAge() {
let gradDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date3').value);
let birthdate = new Date(document.querySelector('#date3').value);
document.querySelector('#result2').value = gradDate.getFullYear() - birthdate.getFullYear();
}
// set some default values
let today = new Date();
document.querySelector('#date1').value = today.toISOString().split('.')[0];
document.querySelector('#result1').value = today.getFullYear();
document.querySelector('#date2').value = today.toISOString().split('.')[0];
let birthdate = new Date(today.getTime);
birthdate.setFullYear(1984);
console.log(birthdate.toISOString().slice(0, 10).replace(/\//g, "-"));
document.querySelector('#date3').value = birthdate.toISOString().slice(0, 10).replace(/\//g, "-");
updateAge();
<input id="date1" type="datetime-local" onchange="updateGradYear(event)" />
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="number" readonly="true" name="year" placeholder="=(getFullYear from date1)" />
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" onchange="updateAge()" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" onchange="updateAge()" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)" /></textarea>
<label for="result2">age</label>
<br />

Let me know how this works for you! And as i said please enter all the fields while running this code!
$('#date1, #date2').on('blur',function(){
var dc = document.querySelector('input[id="date1"]');
var date = new Date(dc.value);
var collegeadmission = date.getFullYear();
$('#result1').val(date.getFullYear());
dc = document.querySelector('input[id="date2"]');
date = new Date(dc.value);
var collegegrad = date.getFullYear();
if(! isNaN(collegegrad))
$('#result2').val(collegegrad - collegeadmission);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />

check out this url:http://jsbin.com/vebiwogipu/edit?html,js,output
Make sure u fill all the dates and time properly as you discussed in your html.
Similarly you can attach the output on click or change event.
and aso you can leverage getMonth() and getDay() in the code to get desired output.

Take a look at the label and may be alert, when you click the button, it shows year out of your first date field. As i said you need to add the logic for rest.
let me know if it makes sense, if not please add more information to make me understand!

Related

Bootstrap Date Picker Validation

Hey guys I am working on a project that requires validation of the date picker to check whether the end date is greater than or equal to the start date! Can anyone help me with how to write jquery for it so that I can disable the dates based on the user's date selection restricting him/her to choose the dates within the starting and ending range entered by the user?
The code looks like this:
<div class="mb-4">
<label for="startdate" class="form-label">StartDate</label>
<input type="date" class="form-control" id="startdate" name="startdate" />
</div>
<div class="mb-4">
<label for="enddate" class="form-label">End Date</label>
<input type="date" class="form-control" id="enddate" name="enddate" />
</div>
I'm not sure how to disable inside picker dates that are higher than the startDate, but like this you can do a validation
var startDate = new Date($('#startdate').val());
var endDate = new Date($('#enddate').val());
if (startDate < endDate){
// Do something
}

Subtract 1 day from date input box and submit using button

I'm trying to collect 2 dates using input boxes ids From and To. I would like to subtract 1 day from the date value received using "FROM" text box and pass that new value to the button click event.
The code below works to push values received from the input box. However, i wish to subtract 1 day and pass on the same.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
From : <input type="date" class="form-control" id="From" placeholder="From" aria-label="From">
To : <input type="date" class="form-control" id="To" placeholder="To" aria-label="To">
<input type="button" onclick="location.href='#SITE#/TDL-Test-code.aspx?FromTo=(Date ge datetime%27'+FD+'T00:00:00.000Z%27) and (Date le datetime%27'+ document.getElementById('To').value+'T23:59:00.000Z%27)';" value="Submit" />
Edit:
Following is my moment JS function
var oldfrom = document.getElementById('From').value;
newdate = moment(oldfrom).subtract(1, 'days').format("YYYY-MM-DD");
var FD = newdate;
Issue was fixed with solution below.
document.getElementById("From_Local").oninput = function() {
var dateLocal = document.getElementById("From_Local").value;
var dateUTC = moment.utc(dateLocal).subtract(4, 'hours').format("YYYY-MM-DD");
document.getElementById("From_UTC").value = dateUTC;
}
From:<input name="From" required type="date" id="From_Local">
<input type="hidden" id="From_UTC">
To:<input name="To" required type="date" id="To">
<input type="button" onclick="location.href='SITE_URL?FromTo=(Date%20ge%20datetime%27'+ document.getElementById('From_UTC').value+'T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%27'+ document.getElementById('To').value+'T00:00:00.000Z%27)';" value="Submit" />

auto change birth date if given birth date given?

I have 2 input one is input for "Birth Date" and the one is for the Age, is there anyway, if I change the Birth Date, the Age input automatically change.
<input type="text" name="birthdate" value="07/24/1988" />
<input type="text" name="age" value="32" />
You can calculate the difference of current date and the date entered in years and then change the value of the age on keyup event like below
function age(dt) {
var diff = ((new Date().getTime() - new Date(dt).getTime()) / 1000) / (60 * 60 * 24);
document.getElementById("age").value = Math.abs(Math.round(diff / 365.25));
}
<input type="text" name="birthdate" value="07/24/1988" onkeyup="age(this.value)" />
<input type="text" name="age" value="32" id="age" />

Validate <input type ="date">

How can I check the <input type="date"> to verify if it exceeds today's date or not before submitting ?
The form will not submit if future date is in the input,
<html>
<head>
</head>
<body>
<form>
<ul>
<li>
<label>Member Since </label>
<input id="since" name="since" size="2" maxlength="6" value="" type="date" required />
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" onclick="checkDate();" />
</li>
</ul>
</form>
</body>
</html>
Try converting the input value to a Date Object to compare today and the input value in your script.
input = document.getElementById("since"); // gets element
value = input.value; // form value (string)
date = new Date(value); // converts string to date object
now = new Date(); // current date
if (now > date) {
// in past
} else {
// in future
}
You need to check two things. 1) was a valid date entered, 2) is the date in the range you want it. try the code bellow, it will check for both conditions before allowing a submit.
<html>
<head></head>
<body>
<script>
function checkDate() {
var val = new Date(document.forms["frm"]["since"].value);
var now = new Date();
if (isNaN(val.getTime()) || (val>now)) {
alert('invalid date');
return false;
}
return true;
}
</script>
<form name="frm" onsubmit="return checkDate()">
<ul>
<li>
<label>Member Since </label>
<input id = "since" name="since" size="2" maxlength="6" value="" type="date" required/>
</li>
<li>
<input type="Submit" name="Submit" id="btnsubmit" value="Submit" />
</li>
</ul>
</form>
</body>
</html>
Something like that should help you.
var dateText = document.getElementById('since').value;
var date = new Date(dateText);
var now = new Date();
if (date > now) {
console.log("Date needs to be in the past");
}

How to disable the already selected date for next date box in J.T.Sage DateBox

I my application i use jt.sage DateBox. I want to disable the already selected datepicker for next date box fields for example my Date1 is like 13.08.14 my other date box fields need to select after 13.08.14 (NOTE : depends on previous date fields).
Here is the FIDDLE FOR date box demo.
It has lot of options like prevent tomorrow and yesterday day but not include after select the current date
<label for="mydate">Date 1</label>
<input id="date1" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}' onclick="filterDate(this.id);"/>
<label for="mydate">Date 2</label>
<input id="date2" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}' onclick="filterDate(this.id);"/>
<label for="mydate">Date 3</label>
<input id="date3" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}' onclick="filterDate(this.id);"/>
<label for="mydate">Date 4</label>
<input id="date4" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}' onclick="filterDate(this.id);"/>
<label for="mydate">Date 5</label>
<input id="date5" type="date" data-role="datebox" data-options='{"mode": "datebox", "useNewStyle":true}' onclick="filterDate(this.id);"/>
How to do this please help to solve this one.
Hope this helps you : http://jsfiddle.net/QTuma/52/
Just change in the logic for difference calculation:
Start Date
// Get the difference
var diff = parseInt((((startDate.getTime() - todaysDate.getTime()) / lengthOfDay)+2)*-1,10);
And End Date
// Get the difference
var diff = parseInt((((endDate.getTime() - todaysDate.getTime()) / lengthOfDay)),10);
This will work for the statement 'example my start date is like 13.08.14 my end date box fields need to select after 13.08.14 .'
I have updated your code based on below reference,
http://jsfiddle.net/ktbcP/528/
This should solve your issue,
http://dev.jtsage.com/jQM-DateBox/doc/6-2-link/
Hope it helps !!

Categories

Resources