The requirement is I have two date fields:
One is effective date and date of birth. When I select the effective date on the page.
The age field should do the following calculation.
That is age would be Effective date - date of birth. the result should be set to the age field.
How to do in javascript or JQuery?
I'm using tapestry front end. So in the HTML page I want to do this setting of value to age field.
You need to convert your dates into milliseconds and subtract them, then calculate the age.
HTML
<input type="date" id="effective" />
<input type="date" id="born" />
jQuery
function getTime(date){
var dateArr = date.split('-');
return new Date(dateArr[0], dateArr[1], dateArr[2]).getTime();
}
function calcDate(date1,date2) {
var eff_date = getTime(date1);
var born_date = getTime(date2);
var diff = Math.floor(eff_date - born_date);
var day = 1000* 60 * 60 * 24;
var days = Math.floor(diff/day);
var months = Math.floor(days/31);
var years = Math.floor(months/12);
return years
}
$("input[type=date]").change(function(){
if($("#effective").val() != "" && $("#born").val() != ""){
var age = calcDate($("#effective").val(),$("#born").val())
alert(age);
}
});
Check out this Fiddle..
Related
I have a form where user can set a date and time with input format datetime-local. When the form is submitted an error appears for the start-date "Value must 11:52 AM or earlier". My local time is 13:52. I have to select -2 hours. How can I remove this problem?
The form is limited for the start date to select only today and last 72 hours, same for end time.
<input type="datetime-local" name="start_timestamp" id="start_timestamp" required>
<input type="datetime-local" name="end_timestamp" id="end_timestamp" required>
<script>
//Do not let to select END-TIME and START TIME in the PAST
var today = new Date();
var past = new Date(today.setDate(today.getDate() - 3)).toISOString().slice(0, 16);
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("start_timestamp")[0].min = past;
document.getElementsByName("start_timestamp")[0].max = today;
</script>
<script>
var today = new Date();
var future = new Date(today.setDate(today.getDate() + 3)).toISOString().slice(0, 16);
var today = new Date().toISOString().slice(0, 16);
document.getElementsByName("end_timestamp")[0].min = today;
document.getElementsByName("end_timestamp")[0].max = future;
</script>
I have an image also:
Your issue is timezone related. Because you're using toISOString to set the input value, it's being set to UTC date and time, not local. So create a function to return the local time in the correct format.
E.g.
// Format date as YYYY-MM-DDTHH:mm in local timezone
// to use to set min and max values for inputs
function toISOLocal(date = new Date()) {
return date.toLocaleString('sv').slice(0,-3).replace(' ','T');
}
/* Initialise date inputs to local dates ± perid in days
* Start is set to "now", end it set to now ± period
* #param {string} startID
* #param {string} endID
* #param {number} period - ±days from start to end
*/
function initialiseDateInputs(startID, endID, period) {
let startEl = document.querySelector('#' + startID);
let endEl = document.querySelector('#' + endID);
// Ensure elements exist
if (!startEl || !endEl) return;
// Create min and max timestamps
let d = new Date();
// Create max with zero'd seconds, milliseconds
let minD = toISOLocal(new Date(d.setSeconds(0,0)));
// Create min ±period days from max
let maxD = toISOLocal(new Date(d.setDate(d.getDate() + period)));
// If period is -ve, swap max and min
if (period < 0) {
[minD, maxD] = [maxD, minD];
}
// Set element attribute values
startEl.setAttribute('max', maxD);
startEl.setAttribute('min', minD);
startEl.setAttribute('value', period < 0? maxD : minD);
endEl.setAttribute('max', maxD);
endEl.setAttribute('min', minD);
endEl.setAttribute('value', period < 0? minD : maxD);
}
// Run when elements should exist
window.onload = () => {
initialiseDateInputs('startDate', 'endDate', +3);
}
.screenTip {
font-family: sans-serif;
color: #bbbbbb;
}
input {
font-size: 150%;
}
<form>
<span class="screenTip">Start date and time, must be within last 3 days</span><br>
<input type="datetime-local" name="startDate" id="startDate" required><br>
<span class="screenTip">End date and time, must be within last 3 days</span><br>
<input type="datetime-local" name="endDate" id="endDate" required><br>
<input type="reset">
</form>
Setting the input value attribute means that if the inputs are in a form and it's reset, they'll return to the min and max values appropriately.
This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 6 years ago.
I'm making simple application for record internal leaves of my office. with this application I have to provide users to two HTML date fields for select start leave date and end leave date. At the same time I need to calculate how many days have in between user's selection also this count may exclude the weekdays. To do this i tried to use simple javascript with one of date fields onchange event but it's not working
this is the complete code with HTML I have tried
<html >
<head>
</head>
<body>
<form action='reqprocess.php' method='post'>
<td><input type="date" name="datepicker" class='form-control' id="startd" required/> <br>
<td><input type="date" name="datepicker2" class='form-control' id="endd"required /> <br>
<td><input type="text" name='leavehmd' class='form-control' id="lhmd"/><br>
<input type='submit' value='Apply' class='btn btn-primary' />
</form>
<script type="text/javascript">
var chng1 = document.getElementById("endd");
chng1.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
var chng2 = document.getElementById("startd")
chng2.onchange = function () {
var date1 = Date.parse(document.getElementById("startd").value);
var date2 = Date.parse(document.getElementById("endd").value);
if (date1 && date2) {
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//alert(diffDays);
document.getElementById("lhmd").value = diffDays;
}
}
</script>
</body>
</html>
But when sect second date, on-change function not works and Input field suppose to fill with counted dates not populated. How can I fix this ?
or how can I achieve this via methods like ajax or jquery
You need to make sure there is a value in each input field before attempting to calculate the difference
You can check this by setting a conditional with the values as the operands. They will evaluate to falsy if there is no value and truthy if there is a value. If both values are present, you can then calculate the difference.
The linked duplicate question has a good clean way to count days between dates:
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var chng1 = document.getElementById("endd");
var chng2 = document.getElementById("startd");
chng1.onchange = displayCurrentDayDifference();
chng2.onchange = displayCurrentDayDifference();
function displayCurrentDayDifference() {
var date1 = document.getElementById("startd").value;
var date2 = document.getElementById("endd").value;
if (date1 && date2) {
var daysBetween = daydiff(parseDate($('#startd').val()), parseDate($('#endd').val()));
document.getElementById("lhmd").value = daysBetween;
}
}
How can I check that a date is greater than or less than the specified date using javascript by passing the month and year only in MMM-YYYY Format.
For example :
Let the user selects JUL from month dropdown and 2016 from years dropdown ,
Now How can I check that the selected values are greater than / less than JUN 2016 .
I've taken the input in Session variables as session("month") , session("yrs").
I've tried the following but nothing happens :
var d1 = new Date('JUN-2016')
var d2 = new Date(<% =session("month")+"-"+session("yrs") %>) )
if(d2.getTime() > d2.getTime())
{
alert('Greater than jun 2016');
}
else
{
alert('Less than jun 2016');
}
I've gone through this link Compare two dates with JavaScript but didn't find the solution for my condition.
As this application is developed on VB so i don't have much knowledge about that.
How can I resolve this .
Please suggest
Thanks in advance.
Try this -
var x = new Date('JUN-2016');
var y = new Date('MAY-2016');
console.log(+x < +y);
console.log(+x > +y);
console.log(+x === +y);
First convert it to date object
// convert to a parseable date string:
var dateStrA = "28/12/2013 16:20:22".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
var dateStrB = "28/12/2013 16:20:11".replace( /(\d{2})\/(\d{2})\/(\d{4})/, "$2/$1/$3");
// now you can compare them using:
new Date(dateStrA) > new Date(dateStrB);
var date1 = Math.ceil(Math.abs(first date) / (1000 * 3600 * 24));
var date2 = Math.ceil(Math.abs(second date) / (1000 * 3600 * 24));
if(date1 > date2 )
alert("date1");
else
alert("date2");
You just have to do a simple compare of dates. Please read more about "Date" here: http://www.w3schools.com/js/js_date_methods.asp
Maybe this code might help:
var day = 1; // Since you don't care about the day just use the first day
var month = session("month"); // Use the number of the month instead of the name
var year = session("yrs");
var dateJune = Date.parse("2016-07-01"); // June
var dateInput = Date.parse(year + "-" + month + "-" + day);
// Compare dates
if (dateJune > dateInput) {
// The input is before june
} else if (dateJune < dateInput) {
// The input is after june
} else {
// It is june
}
You need a valid date format to be able to parse the date. Instead of getting "JUN" from your select box it would be better to get the number of the month instead. A select box should look like this:
<select>
<option value="01">Jan</option>
<option value="02">Feb</option>
...
</select>
If this is not an option you can use a function that calculates the number for you if you know then string values that your month variable might have:
function (nameOfMonth) {
switch (nameOfMonth) {
case 'Jan':
return "01";
case 'Feb':
return "02";
....
}
}
I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle
Can't seem to find the problem. Every time I run it I get NaN for ageDale, been looking at it for a while now, its probably simple but I appreciate the help!
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
<input type="text" id="birthDate">
Current Date
<input type="text" id="currentDate">
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
<script>
function test() {
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
alert(ageDale)
}
</script>
Also, is it necessary for me to have that else statement? or is there another way to set up this so its not needed?
This
ageDate.value
should be
ageDate
only. It's a variable and already contains only the difference from
birthDate.value - currentDate.value
if(ageDate.value < 1) {
// ^ here
(ageDale = ageDate.value * -1)
} //^ here
else {
(ageDale = ageDate.value * 1)
// ^ and here
You only need to fetch the value when getting data from, for example, input fields.
Also (depending on how you input them) it might be a problem to calculate dates. For debugging purposes you should
console.log()
your variable values, that way you will find out quickly where the error is.
A good place for a console.log() in your code would be, for example after this block:
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
console.log(ageDate);
SIDENOTE:
You might want to take a look at moment.js, which will help you with date calculations. For example, you can get differences between dates with moment.js like this:
var a = moment([2014, 12, 05]);
var b = moment([2014, 12, 06]);
a.diff(b, 'days') // 1
Try this:
var btn = document.getElementById("Submit_Button");
btn.onclick = function test() {
var birthDate = parseInt(document.getElementById("birthDate").value);
var currentDate = parseInt(document.getElementById("currentDate").value);
var ageDate = (birthDate - currentDate);
if(ageDate < 1) {
(ageDate = ageDate * -1)
}
else {
(ageDate = ageDate * 1)
}
alert(ageDate)
}
As baao said, you have spelling errors. After correcting those, you want to consider what your input is going to be, and make sure you are checking that the input is valid.
For example, if I type "September 10th" for my birthday and "December 10th" for the current date, your function will try and subtract two strings which is not valid. If you're going to use a custom input field for the date, you need to be sure its in a consistent and parseable format.
I'd recommend asking for just their birthday in a specific format and parsing it from there, since we can use Javascript to get the current date easily. For example, mm-dd-yy. We may re-write it as:
function test() {
//lets get the date, in the format 'mm-dd-yy'. You'd want to do error checking at some point if you're serious about it
var dateInput = document.getElementById("birthDate").value;
//get each individal date type by splitting them at the -, giving ['dd', 'mm', 'yy']
var dateSplit = dateInput.split('-');
//create a Javascript date object with the date we got
var birthDate = new Date(dateSplit[2], dateSplit[0], dateSplit[1]);
//create another with the current date and time
var currentDate = new Date();
// find the difference in milliseconds
var dateDifference = Math.abs(birthDate.getTime() - currentDate.getTime());
// convert to years
var age = dateDifference / (1000 * 3600 * 24 * 365);
alert(age);
}
<p>Enter names in the fields, then click "Submit" to submit the form:</p>
<form name="form">
Birth Date (dd-mm-yy):
<br>
<input type="text" id="birthDate">
<br>
<a id="Submit_Button" onclick="test();" href="javascript:void(0);" title="Submit">Submit</a>
</form>
just modify this code
var birthDate = document.getElementById("birthDate");
var currentDate = document.getElementById("currentDate");
var ageDate = (birthDate.value - currentDate.value);
if(ageDate.value < 1) {
(ageDale = ageDate.value * -1)
}
else {
(ageDale = ageDate.value * 1)
}
with this
var vbirthdate = new Date(document.getElementById("birthDate").value);
var vcurrentdate = new Date(document.getElementById("currentDate").value);
var ageDate = Math.floor((vbirthdate-vcurrentdate)/(1000*60*60*24));
if(ageDate < 1) {
(ageDate = ageDate * -1)
} // no need to do something like this (ageDate *1) if it is already a positive number, just check if it's a negative then convert it to a positive number
you can try the code at http://jsfiddle.net/kapasaja/duco4cqa/5/
what you asking is similar to this post