Update Birthday using Year and Month values - javascript

I'm trying to display and update a child's age through a MM/dd/YYYY textbox, and simple int values in year(s) and month(s) textboxes.
So if a child had a birthday of: 02/03/2015, and I'm comparing against today's date of 03/07/2018, the Year textbox should say 3 and the month textbox should say 1
If you were to change the year value to 5, the DoB value should change to 02/03/2013.
If you were to then change the month value to 9, the DoB value should change to 05/03/2012.
If I were to change the DoB value, the Year and Month textbox should also change to the appropriate values.
The day value should be persisted, and changed to 01 when it can't.
I would like to of course account for odd date arithmetic.
What I have so far in my C# MVC app is that I have a ChildViewModel object with these properties:
DateTime? DateOfBirth
public int AgeMonths
public int AgeYears
On my view, I have a textbox for each of these values.
<div class="row">
<div class="form-group">
#Html.LabelFor(m => m.DateOfBirth, new { #class = "control-label" })
#Html.TextBoxFor(m => m.DateOfBirth, "{0:MM/dd/yyyy}", new { #class = "form-control", placeholder = "Child's Date of Birth", onchange = "determineAge(this.id, null, null)" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AgeYears, new { #class = "control-label" })
#Html.TextBoxFor(m => m.AgeYears, new { #class = "form-control", placeholder = "x years and...", onchange = "determineAge(null, this.id, null)" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.AgeMonths, new { #class = "control-label" })
#Html.TextBoxFor(m => m.AgeMonths, new { #class = "form-control", placeholder = "...y months old", onchange = "determineAge(null, null, this.id)" })
</div>
</div>
Here is my JavaScript so far, slightly altered to work in the snippet, using a little bit of moment.js v2.21.0
https://jsfiddle.net/RyanTaite/fak22xrf
The snippet below is effectively the same code:
function determineAge(dobId, ageYearsId, ageMonthsId) {
///<summary>Updates the Date of Birth, Years, and/or Months text box(es) based on what's passed in. It's likely terribly written and I'd welcome a rewrite by someone better at date math. Dependant on moment.js</summary>
var dobValue = null;
var yearValue = null;
var monthValue = null;
var today = new Date();
// Update DOB, AgeYears, and AgeMonths based on who was changed
if (dobId !== null) {
dobValue = new Date(document.getElementById(DateOfBirth.value));
var ageInMonths = today.getMonth() - dobValue.getMonth() + (12 * (today.getFullYear() - dobValue.getFullYear()));
yearValue = Math.floor(ageInMonths / 12);
monthValue = ageInMonths % 12;
document.getElementById('AgeYears').value = yearValue;
document.getElementById('AgeMonths').value = monthValue;
} else if (ageYearsId !== null) {
yearValue = document.getElementById('AgeYears').value;
monthValue = document.getElementById('AgeMonths').value;
dobValue = new Date(document.getElementById('DateOfBirth').value);
dobValue.setFullYear(today.getFullYear() - yearValue);
document.getElementById('DateOfBirth').value = dobValue.toLocaleDateString();
} else if (ageMonthsId !== null) {
dobValue = new moment(new Date());
monthValue = parseInt(document.getElementById('AgeMonths').value);
yearValue = parseInt(document.getElementById('AgeYears').value);
var dayValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY").get('date');
var totalMonths = monthValue + (yearValue * 12);
dobValue.subtract(totalMonths, "months");
// This is the proper way to set the day value of a moment object, you have to chain your way there
dobValue.year(dobValue.get('year')).month(dobValue.get('month')).date(dayValue);
document.getElementById('DateOfBirth').value = moment(dobValue._d).format("MM/DD/YYYY");
}
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="control-label">Date of Birth</div>
<input class="form-control" id="DateOfBirth" placeholder="Child's Date of Birth" onchange="determineAge(this.id, null, null)"></input>
</div>
<div class="form-group">
<div class="control-label">Years</div>
<input class="form-control" id="AgeYears" placeholder="x years and..." onchange="determineAge(null, this.id, null)"></input>
</div>
<div class="form-group">
<div class="control-label">Months</div>
<input class="form-control" id="AgeMonths" placeholder="...y months old" onchange="determineAge(null, null, this.id)"></input>
</div>
</div>
It's buggy and likely terribly written, so I'd love some help with this.

I believe I fixed it using diff and general moment properties more, as Matt's comment suggested.
If nothing else, it's cleaner and closer to what I wanted.
I welcome anyone's suggestions or edits to improve this.
function determineAge(dobId, ageYearsId, ageMonthsId) {
///<summary>Updates the Date of Birth, Years, and/or Months text box(es) based on what's passed in. Dependant on moment.js</summary>
var dobValue = null;
var yearValue = null;
var monthValue = null;
var today = new moment();
// Update DOB, AgeYears, and AgeMonths based on who was changed
if (dobId !== null) {
dobValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY");
yearValue = new moment().diff(dobValue, 'years');
monthValue = new moment().diff(dobValue, 'month') % 12;
document.getElementById('AgeYears').value = yearValue;
document.getElementById('AgeMonths').value = monthValue;
} else if (ageYearsId !== null || ageMonthsId !== null) {
yearValue = parseInt(document.getElementById('AgeYears').value);
monthValue = parseInt(document.getElementById('AgeMonths').value);
dobValue = new moment(document.getElementById('DateOfBirth').value, "MMDDYYYY");
const ageInMonths = (yearValue * 12) + (monthValue);
const todayMinusMonths = today.subtract(ageInMonths, 'months');
const dayValue = dobValue.date();
dobValue = todayMinusMonths;
dobValue.date(dayValue);
document.getElementById('DateOfBirth').value = dobValue.format("MM/DD/YYYY");
}
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="form-group">
<div class="control-label">Date of Birth</div>
<input class="form-control" id="DateOfBirth" placeholder="MM/dd/YYYY" onchange="determineAge(this.id, null, null)">
</div>
<div class="form-group">
<div class="control-label">Years</div>
<input class="form-control" id="AgeYears" placeholder="x years and..." onchange="determineAge(null, this.id, null)">
</div>
<div class="form-group">
<div class="control-label">Months</div>
<input class="form-control" id="AgeMonths" placeholder="...y months old" onchange="determineAge(null, null, this.id)">
</div>
</div>

Related

How to set date mask in fields

How can I set mask on date fields, date from and date to.
Here is my code below
<div class="col-md-6">
Year_from
#Html.TextBoxFor(model => model.yfrom, new { #class = "form-control", maxlength = "10", minlength="4" })
</div>
<div class="col-md-6">
Year_to
#Html.TextBoxFor(model => model.yto, new { #class = "form-control", maxlength = "10", minlength = "4" })
</div>
<script>
jQuery(function ($) {
$("#yfrom").mask("99.99.9999");
$("#yto").mask("99.99.9999");
});
var v = this.value;
if (v.match(/^\d{2}$.) !== null) {
this.value = v + '.';
} else if (v.match(/^\d{2}\/\d{2}$.) !== null) {
this.value = v + '.';
}
</script>
</div>
I tried to include jQuery function to this, but still not working, I need something that would show error on date field when someone input wrong values in first field and switch to another one.

Changing a ISO date to a Short date JavaScript

I currently have a function setup to get the following two weeks or months from the selected date from a input date field. However, the problem I'm facing is that I want to get the date to output DD/MM/YYYY but I'm getting the full ISO date where I need the short. Does anyone know how I can go about doing this?
EDIT:
I've added the moment(date1).format('DD/MM/YYYY'); to test the code but this hasn't provided any results.
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
moment(date1).format('DD/MM/YYYY');
var date2 = new Date(date1);
date2.setMonth(date2.getMonth() + 1);
document.getElementById("pM1").innerHTML = date1;
document.getElementById("pM2").innerHTML = date2;
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var date2 = new Date(date1);
date2.setDate(date2.getDate() + 7);
document.getElementById("pW1").innerHTML = date1;
document.getElementById("pW2").innerHTML = date2;
}
}
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
First off, you are setting the input value to the current date right here
var dateSelected = document.getElementById('datePicker').valueAsDate = new Date();
don't do that, it kind of defeats the purpose of having a selector in the first place.
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US" as the locale:
console.log((new Date()).toLocaleDateString('en-US')); // format MM/DD/YYY
I also fixed how you set the new dates, it now takes one date and adds either one and two months or one and to weeks instead of none and one month and none and one week ;-)
function submit() {
var type = document.getElementById("selectType").value;
var dateSelected = document.getElementById('datePicker').valueAsDate;
if (type === "Months") {
document.getElementById("pWeeks").className = "hidden";
document.getElementById("pMonths").className = "";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setMonth(date1.getMonth() + 1);
var datePlusTwo = new Date(date1);
datePlusTwo.setMonth(date1.getMonth() + 2);
document.getElementById("pM1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pM2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
} else {
document.getElementById("pWeeks").className = "";
document.getElementById("pMonths").className = "hidden";
var date1 = dateSelected;
var datePlusOne = new Date(date1);
datePlusOne.setDate(date1.getDate() + 7);
var datePlusTwo = new Date(date1);
datePlusTwo.setDate(date1.getDate() + 14);
document.getElementById("pW1").innerHTML = datePlusOne.toLocaleDateString('en-US');
document.getElementById("pW2").innerHTML = datePlusTwo.toLocaleDateString('en-US');
}
}
.hidden {
display: none;
}
<input type="date" id="datePicker"><br>
<select id="selectType">
<option value="Months">Months</option>
<option value="Weeks">Weeks</option>
</select><br>
<button id="submit" onclick="submit()">Submit</button>
<div id="pMonths" class="">
<p id="pM1"></p>
<p id="pM2"></p>
</div>
<div id="pWeeks" class="">
<p id="pW1"></p>
<p id="pW2"></p>
</div>
Instead of document.getElementById("pM1").innerHTML = date1; you should build first a string with the methods provided by the date object ( getFullYear, getDate, getMonth; see docu ). Then you can assign the string to the innerHtml.
If you can use the moment.js then your code which you assign to your innerHtml is date1 = moment(dateSelected).format('DD/MM/YYYY')
Also I would recommend Luca's way:
As for converting the Dates, I would use Date.prototype.toLocaleDateString() passing "en-US"
which would look at your code:
dateSelected.toLocaleDateString('en-US')
You could use MomentJS library to keep things simple:
Include the library :
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
document.getElementById("pM1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pM2").innerHTML = moment(date2).format('DD/MM/YYYY');
and in the else:
document.getElementById("pW1").innerHTML = moment(date1).format('DD/MM/YYYY');
document.getElementById("pW2").innerHTML = moment(date2).add(1, 'week').format('DD/MM/YYYY');

Alert message if date and time is older than a value

I have a form with a date and time field, the date field consists of 3 fields: day, month and year. And time field consists of 2 fields, hour and minute.
I want to show an alert if the date is older than 2 months and 60 hours.
HTML:
<div class="container-date">
<div class="date_day">
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
I can do it with one field only for date, but have now 3 fields that I need.
I tried something like this:
jQuery(document).ready(function($){
var day = $('#input_day');
var month = $('#input_month');
var year = $('#input_year');
var today = new Date();
var currentMonth = today.getMonth();
month.on("input change", function() {
if ((today.getMonth() + 11) - (this + 11) > 4) {
console.log('test');
}
});
});
I'd suggest you to parse the form date, create the comparison date according to the expected period and then return if the formDate is greater than comparisonDate.
Please, let me know if the code below is according to what you expected:
function getFormDate() {
const formYear = $("#input_year").val();
const formMonth = $("#input_month").val() - 1;
const formDay = $("#input_day").val();
const formHour = $("#input_hour").val();
const formMinute = $("#input_minute").val();
return new Date(formYear, formMonth, formDay, formHour, formMinute, 0, 0)
}
function getComparisonDate() {
const today = new Date()
let comparisonDate = new Date()
comparisonDate.setMonth(today.getMonth() - 2)
comparisonDate.setHours(today.getHours() - 60)
return comparisonDate
}
function thereIsMissingValue() {
let anyMissing = false;
const inputs = $(".container-date input, .container-time input")
inputs.each(function () {
if (!$(this).val())
anyMissing = true
});
return anyMissing
}
function displayMessage() {
const formDate = getFormDate()
const comparisonDate = getComparisonDate()
$("#min-allowed-date").text(comparisonDate.toLocaleString())
const isOlderThanComparison = formDate < comparisonDate
$(".older-date").toggle(isOlderThanComparison)
const isInTheFuture = formDate > new Date()
$(".future-date").toggle(isInTheFuture)
const isValidDate = !isOlderThanComparison && !isInTheFuture
$(".valid-date").toggle(isValidDate)
}
function calculate() {
if (thereIsMissingValue()) {
$(".container-date-validation").hide()
return
}
$(".container-date-validation").show()
displayMessage()
}
$('#input_year, #input_month, #input_day, #input_hour, #input_minute').change(function () { calculate(); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-date">
<div class="date_day">
<label>Day</label>
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<label>Month</label>
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year">
<label>Year</label>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour">
<label>Hour</label>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<label>Minute</label>
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
<div class="container-date-validation" style="display:none">
<p class="older-date" style="display:none">Invalid date. Only dates after
<span id="min-allowed-date"></span> are allowed.
</p>
<p class="future-date" style="display:none">Invalid date. It doesn't allow dates in the future.</p>
<p class="valid-date">This is a valid date</p>
</div>
If you go with milliseconds :
2 months is 5184000000
60 hours is 216000000
total : 5400000000
the wantedDate will be new Date(year, month, day)
var wantedDate = new Date(year,month,day); // will create a date from the inputs
wantedDate.getTime() // will convert to miliseconds
and if you convert the wanted date to milliseconds you can easily find out
wantedDate < Date.now() && wantedDate > (Date.now() - 5400000000)
I really like using Moment.js for things like this. It uses much more human-readable code, like so:
const moment = require('moment'); // assumes you install Moment as a node module
const month = $('#input_month');
const day = $('#input_day');
const year = $('#input_year');
const hour = $('#input_hour');
const minute = $('#input_minute');
const checkDate = () => {
const inputDate = moment(month.val() + '/' + day.val() + '/' + year.val() + ' ' + hour.val() + ':' + minute.val(), "MM-DD-YYYY HH:mm");
const expDate = moment.subtract(2, "months").subtract(60, "hours");
if (moment(inputDate).isBefore(expDate, "minute") {
// do something
}
}
month.on('change', checkDate);
You'll also need to ensure you're getting usable values from your inputs. I suggest using number input types or select menus to restrict input options.

Javascript Calculate Age from HTML input date type

I am trying to calculate age using Javascript. The choose their date of birth from an HTML date input type and his/her age should be displayed. How can Javascript use the HTML Date input type data and calculate age?
Below is the HTML
<html>
<head>
<title> Sample Date of Birth Registration</title>
<script type="text/javascript" src="formiteration6.js"></script>
</head>
<body>
<h1>Birth Registration</h1>
<hr />
<form id ="inputFrom">
<label for="size_1">D.O.B:</label><input type="date" name="size" id="birthDate" value="dd/mm/yy" />
<input type='button' onclick='regBirth()' value='Add new person' />
</form>
<hr />
<table id="details">
<tr>
<th>Date of Birth</th>
<th>Age</th>
</tr>
</table>
<h4>Statistics</h1>
<hr />
<h5><b>Total Count:</b></h5>
<p id="count"></p>
</body>
</html>
And Javascript is here
var allPeople = [];
function regBirth() {
'use strict';
var myArray = {};
var actualDob = myArray.actualBirthDate;
actualDob = document.getElementById('birthDate').value
allPeople.push(myArray);
var inputForm = document.getElementById("inputFrom").reset();
var tabularForm = document.createDocumentFragment();
var tablerow = document.createElement('tr');
var dob = document.createElement('td');
dob.innerHTML = actualDob;
tablerow.appendChild(dob);
tabularForm.appendChild(tablerow);
document.getElementById("details").appendChild(tabularForm);
var totalPeople = allPeople.length;
document.getElementById("count").innerHTML=totalPeople;
}
Get Today's Date using new Date()
Get Date of Birth using new Date(datestring)
Get Year from both Dates using getFullYear()
Now find the Difference between two Years.
Fiddle Demo
in js
// Make a button that display the current date and time in local format on the page.
function mydateis(){
const d = new Date();
let text = d.toLocaleString();
document.getElementById("date").innerHTML = text;
var year_born = prompt("Please enter your date of birth:", 1998);
var month_born = prompt("Please enter your month:", 1);
var month_day = prompt("Please enter your day:", 1);
function getAge(birthYear,month_born,month_day){
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentmonth = currentDate.getMonth();
var currentday = currentDate.getDate();
console.log(currentDate);
console.log(currentDate.getDate());
age = currentYear - birthYear;
month = currentmonth - month_born;
day = currentday - month_day;
return age,month,day;
}
calculatedAge = getAge(year_born,month_born,month_day);
document.getElementById("yearsold").innerHTML ="you have yeyre is" + age+ " and "+month+" month and days is "+day ;
}
in html
<button onclick="mydateis()">date is </button>
<h4>hekoo date is </h4>
<p id="date"></p>
<p id="yearsold"></p>
the out bot is

how to automatically populate the age field after entering dob filed in jsp.?

My jsp code is as follows:(A simple registartion from with fields)
<label>DOB</label></td><td><input type="text" name="dob" /> </td></tr>
<tr><td>
<label>AGE</label></td><td><input type="text" name="age" onclick =" ageCount()"/> </td></tr>
<tr><td>
<label>GENDER</label></td><td><input type="radio" name="gender" value="Male"/>Male<input
type="radio" name="gender" value="Female">Female</td></tr>
<tr><td>
I used a function in JS to calculate the age from dob! Dob is in sql Date format.
<script type="text/javascript">
function ageCount(){
var date1 = new date();
var dob = document.getElementById("dob").value;
var date2 = new date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(pattern.test(dob)){
var y1 = date1.getFullYear();
var y2 = date2.getFullYear();
var age = y1-y2;
document.write("Age :" +age);
return true;
}else{
alert("invalid date fromat.!! Please enter in (DD/MM/YYYY) format");
return false;
}
}
</script>
how do i use this so that when i enter the dob and press tab the age should be displayed in its field.
Drop in your ideas and suggestions.
<input type="text" name="dob" onBlur="getAge(this.value)"/>
<input type="text" name="age" id="ageId"/>
function getAge(birthDate){
var birthDate= new Date(birthDate);
var currentDate= new Date();
var years = (otherDate.getFullYear() - birthDate.getFullYear());
if (currentDate.getMonth() < birthDate.getMonth() ||
currentDate.getMonth() == birthDate.getMonth() && currentDate.getDate() < birthDate.getDate()) {
years--;
}
$('#ageId').val(years);
}
If the current month less than birth month or equal and currentdate is lessthan birth date i am decreasing years the value
Hey guys thanks for ur time working on my issue!!
I have solved it myself with a few changes here and there.
The modified code :( might help others if need be)
<script type="text/javascript">
function ageCount() {
var date1 = new Date();
var dob = document.getElementById("dob").value;
var date2 = new Date(dob);
var pattern = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
//Regex to validate date format (dd/mm/yyyy)
if (pattern.test(dob)) {
var y1 = date1.getFullYear();
//getting current year
var y2 = date2.getFullYear();
//getting dob year
var age = y1 - y2;
//calculating age
document.getElementById("ageId").value = age;
doucment.getElementById("ageId").focus ();
return true;
} else {
alert("Invalid date format. Please Input in (dd/mm/yyyy) format!");
return false;
}
}
<tr>
<td><label>DOB</label></td>
<td><input type="text" name="dob" id="dob"
onblur="ageCount()" /></td>
</tr>
<tr>
<td><label>AGE</label></td>
<td><input type="text" name="age" id="ageId" /></td>
</tr>
try this
<script type="text/javascript">
function ageCount() {
var today = new Date();
var date1 = document.getElementById("dob").value;
var dob = new Date(date1);
var month = dob.getMonth();
var day = dob.getDate();
var age = today.getFullYear() - dob.getFullYear();
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day))
{
age--;
}
if(age < 0)
{
alert ("Invalid Date of Birth");
return false;
}
else
{
document.getElementById("age").value = age;
doucment.getElementById("age").focus ();
alert(age);
return true;
}
}
</script>
You can use unBlur() function , when you control leave the focus from text box your JavaScript method should be called.
Like this :-
<input type="text" name="age" onblur="ageCount()"/>
Now inside your JavaScript you can calculate the age and display.
<script type="text/javascript">
// Your ageCount() for calculate AGE and display AGE
</script>

Categories

Resources