I am making a calculator that calculates the age in years but I also want to calculate months Please help me with this Regard Thank you. I want my output like this for 22 years and 3 months. I attach my javascript code and Razor view code. In javascript code, only years are calculated and in Razor view, two text boxes in the first text box take the user's DOB and show his age in the other text box. I want to add a code to calculate months also.DOB is not hardcode .
<html>
<body> <div class="form-group row">
<label class="control-label col-sm-2" asp-for="Dob">Birth date:</label>
<div class="col-sm-5"> <input asp-for="Dob" id="txtDOB" asp-format="{0:yyyy-MM-dd}" class="form-control" placeholder="YYYY-MM-DD" /> </div>
</div>
\<div class="form-group row"\>
\<label class="control-label col-sm-2" for="Age"\>Age:\</label\>
\<div class="col-sm-5"\>
\<input type="text" id="age" asp-for="Age" class="form-control" /\>
\</div\>
\</div\>
</body>
</html> <script src="~/Scripts/jquery-3.4.1.js"></script> <script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#txtDOB").change(function () {
var dob = $("#txtDOB").val();
if (dob == null || dob == "") {
} else {
$("#age").val(getAge(dob));
}
});
function getAge(birth) {
ageMS = Date.parse(Date()) - Date.parse(birth);
age = new Date();
age.setTime(ageMS);
ageYear = age.getFullYear() - 1970;
return ageYear;
}
});
</script>
I want when the user to enter the DOB at run time and then the text
box to show the age. In this code, DOB is hard to code.var birth = new
Date("08 Nov 2020 00:00:00 GMT")
Based on your code and comment It seems that you are trying to calculate age what user select in calender and calculate the age autometically along with the month. You can do that both using C# and Javascript. Here is the elegant way to do that using C#, Jquery and Ajax which is more easy and flexible in ragards of formating.
Calculate Age Method:
public object CalculateAge(DateTime dateOfBirth)
{
//DateTime birth = new DateTime(1988, 08, 02);
DateTime birth = dateOfBirth;
DateTime today = DateTime.Now;
TimeSpan span = today - birth;
DateTime age = DateTime.MinValue + span;
// Make adjustment due to MinValue equalling 1/1/1int years = age.Year - 1;
int months = age.Month - 1;
int days = age.Day - 1;
// Print out not only how many years old they are but give months and days as well
var ageInYMD = string.Format("{0} years, {1} months, {2} days", age.Year, months, days);
var ageInYM = string.Format("{0} years, {1} months", age.Year, months);
var ageInY = string.Format("{0} years", age.Year);
return ageInYM;
}
Note: Importantly it will provide you more flexibility to format the date as you want.
Controller:
public IActionResult ViewCalculateAgeJquery() // This is to load view
{
return View();
}
[HttpGet]
public ActionResult CalulateAgeFromDob(DateTime dateOfBirth) // This controller will be called once the age selected.
{
var age = CalculateAge(dateOfBirth);
return Json(age);
}
View:
#model DotNet6MVCWebApp.Models.CalculateAgeModel
<div>
<table class="table table-sm table-bordered table-striped">
<tr>
<th> <label asp-for="DoB"></label></th>
<td> <input asp-for="DoB" id="dateOfBirth" class="form-control" placeholder="Enter date of birth" /><span asp-validation-for="DoB"></span></td>
</tr>
<tr>
<th> <label asp-for="Age"></label></th>
<td> <input asp-for="Age" id="Age" class="form-control" readonly placeholder="Calculated age" /><span asp-validation-for="Age"></span></td>
</tr>
</table>
</div>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
$('#dateOfBirth').change(function () {
var dateOfBirth = $('#dateOfBirth').val();
console.log(dateOfBirth);
$.ajax({
url: '/CalculateAge/CalulateAgeFromDob',
type: 'GET',
dataType: 'json',
data: { dateOfBirth: dateOfBirth },
success: function (response) {
console.log(response);
$("#Age").val(response);
alert(response);
},
error: function () {
alert('Error!');
}
});
});
});
</script>
}
Model:
public class CalculateAgeModel
{
public DateTime DoB { get; set; }
public string Age { get; set; }
}
Output:
It will help you to implement as per your requirement.
You can use this to get the difference in months (total months):
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth();
months += d2.getMonth();
return months <= 0 ? 0 : months;
}
Use devision (by 12) to get the full years difference, then use modulo to get the remaining months.
var totalMonths = monthDiff(d1, d2);
var years = Math.floor(totalMonths / 12);
var months = totalMonths % 12;
Example fiddle: http://jsfiddle.net/v0dn64rk/
Related
Can I do a warning validate from Datepicker and alert swal like this?
I do that and it error that is_string is not defined.
I'm new in php btw
The comment is a think that i tried to make in different way sorry abort that.
form
<div class="form-group">
<label>Birthdate</label>
<div class="input-group date">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span><input type="text" class="form-control datepicker_class" id="birth_date" name="birth_date" onchange="validateAge">
</div>
</div>
function
function validateAge(){
var birthday = new $('#birth_date').val();
// let birthday = $('#birth_date').val();
// check = explode('/',birthday);
birthday = explode("/", birthday);
// alert(check);
if (is_string(birthday)) {
birthday = strtotime(birthday);
}
// check
// 31536000 is the number of seconds in a 365 days year. strtotime for 1 years : 31556926
if(time() - birthday < 18 * 31556926) {
swal({
title: "warning",
text: "your age is lower than 18",
type: "warning"
});
}
return true;
}
In javascript there is no is_string() function. To check if variable is string you can do it this way:
if (typeof birthday === 'string' || birthday instanceof String)
//string
else
//not string
I have input in html like this:
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
I would like to select a date that is more than 7 days from the current date, if I select a date before 7 days from current, it should prompt saying "Wrong date selected"
How do I do that in javascript?
I tried the following:
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
It gives the date correctly. How do I use this to compare if date is 7 after or not and prompt accordingly?
Thanks!
UPDATE:
<html>
<body>
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
</body>
</html>
<script>
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e)
{
var selectDate = e.target.value
var startDate = new Date(Date.parse(selectDate));
console.log(startDate);
var dateAfter7Days = new Date(new Date().getTime()+(7*24*60*60*1000))
console.log("7 days " + dateAfter7Days);
if (startDate => dateAfter7Days )
{
console.log("Allow");
}
else
{
console.log("Don't allow");
}
}
</script>
I am getting "Allow" for any date I select.
The point is comparing two date values. If current date - selected date > 7 then it should print prompt. The problem is how to get selected date.
You can get the selected date from the input tag by event value. On changed date, the value get logged.
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e) {
console.log(e.target.value);
}
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
var date = new Date();
var next_seven_date = d.getDate()+7;
var current_month = d.getMonth();
current_month++; // month start from 0 then we need to +1
var current_year = d.getFullYear();
var weekDate =(next_seven_date + "/" + current_month + "/" + current_year);
date.setDate(weekDate);
Since your problem is to compare dates not creating them I have updated my answer which might hlp you
var currentDate= new Date();
currentDate= new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),0,0,0)
var idealDifference= (7*24*60*60*1000);
//In your case this date might comes from some date selection user control. Be aware to make the time part of each date to same
var userSelectedDate = new Date(2021, 04, 04,currentDate.getHours(),0,0,0)
if((userSelectedDate.getTime()-currentDate.getTime())>=idealDifference)
{
console.log(userSelectedDate, ' is after 7 days from ',currentDate)
}
else
{
console.log(userSelectedDate, ' is before 7 days from ',currentDate)
}
Note: It is important to unset the time part of both the dates before comparing for this logic to work
I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?
I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}
I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS
Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.