I have three formats stored in database setting table.
<select>
<option value="d-m-Y">dd/mm/yyyy</option>
<option value="Y-m-d">yyyy/mm/dd</option>
<option value="m-d-Y">mm/dd/yyyy</option>
</select>
I am able to get the format value like d-m-Y or Y-m-d or m-d-Y in the line
var dateFormat = getDateFormat(); //of the below code.
function GetAge(dateString)
{
var today = new Date();
var dateFormat = getDateFormat();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
Now I want that it should check format first then calculate the age...
Please help me !!!
You are using jquery ui so before calculation use datepicker.formatDate like this.
var dateFormat = getDateFormat();// Return pattern yy-mm-dd
var today =$.datepicker.formatDate(dateFormat , new Date());;
var birthDate = $.datepicker.formatDate(dateFormat , new Date(dateString));
//Your age calculation logic
Related
I would like to use Geolocation and Date in JavaScript (ECMA) to ask the user where and when they were born and convert this into years. I am asking where they were born because I need to take into account different time zones.
So far, my function returns the number of years the user is old:
function birth() {
var their_birth_day = new Date("18 May 2005"); // Just as an example
var today = new Date();
var ms_old = today.getTime() - their_birth_day.getTime();
var yrs_old = ms_old/3.154e+10;
return yrs_old;
}
But how do I use their location to make it more accurate?
function getAge( dateString ) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
So I need to automatically compute for a person's age by javascript and show it on an asp:textbox. The birthdate is acquired by using jquery-ui's datetimepicker. I expect that I can do arithmetic functions on two date variables so I intend to calculate the age by
var age = Date.Now - $bdate;
What I have done is I converted my bdate to ISO-8601 format because I read that date.parse only works with ISO-8601 compliant format before trying to minus both dates.
Is there anything wrong to what I am thinking?
here's my code:
$('#<%= txtBDate.ClientID%>').change(function () {
var rawr = Date.parse($(#'<%= txtBDate.ClientID%>').val());
$('<%=txtAge.ClientID%>').val(Date.now - rawr);
});
So what made me solve this problem is by calling the day off and rest for the night. I guess coding for how many hours a day makes you tired and dumb.
anyways, here's the code that I made to solve this problem
$('#<%= txtBDate.ClientID%>').change(function () {
var today = new Date();
var curYear = today.getFullYear();
var curMonth = today.getMonth();
var bdate = new Date($('#<%=txtBDate.ClientID%>').val());
var bYear = bdate.getFullYear();
var bMonth = bdate.getMonth();
var age = curYear - bYear;
if (curMonth < bMonth) {
age = age - 1;
}
$('#<%=txtAge.ClientID%>').val(age);
})
function getage() {
var birthday = document.getElementById('birthdate').value // get the birthdate from the birthdate textbox with id = "birthdate"
var dob = birthday ; //insert birthrate into dob variable
var year = Number(dob.substr(0, 4)); // get year from dob variable
var month = Number(dob.substr(4, 2)) - 1; //get month from dob variable
var day = Number(dob.substr(6, 2)); //get day from dob variable
var today = new Date(); // get current date
var age = today.getFullYear() - year; // calculate age
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() <
day)) {
age--;
alert(age);
}
}
I have a requirement where i need to find the date entered in the textfield should not be less than currentdate and future date should not exceed exactly date after 1 year from the eentered date.I have coded for former one but i later requirement i could not do it.
I have posted code for checking less than current date here. Please let me know for checking if the date entered exceed the date after 1 year.
var currentDate = new Date();
var nextDate = new Date();
function checkLessThanCurrentDate() {
//var dateEntered = arguments[0]; -->Will have date that come form textfield
var day = dateEntered.split("/")[0];
var month = dateEntered.split("/")[1];
var year = dateEntered.split("/")[2];
//--->Logic for chekcing date less than current date
if ((year < currentDate.getFullYear() || (month - 1 < currentDate.getMonth() &&
year <= currentDate.getFullYear()) || ((day < currentDate.getDate()) && (month -
1 <= currentDate.getMonth()) &&
(year <= currentDate.getFullYear())))) {
return true;
}
else {
return false;
}
}
Here's how to get the date one year from now:
var now = new Date();
var oneYear = new Date();
var oneYear.setYear(now.getFullYear() + 1);
if (dateEntered > oneYear) {
// logic
}
I think this should work for both your requirements:
function isValidDate(dateToCheck)
{
return isLessThanYearFromToday(dateToCheck) && dateToCheck >= new Date();
}
function isLessThanYearFromToday(dateToCheck)
{
var yearFromToday = new Date();
yearFromToday.setFullYear(yearFromToday.Year + 1);
return dateToCheck <= yearFromToday;
}
you need to use .getTime() method. .getTime() return the time in millisonds
var toDayDate = new Date();
var enteredDate = new Date('06/09/2015'); // mm/dd/yyyy formate
if(toDayDate.getTime()<enteredDate.getTime() && toDayDate.getTime()+(365*24*60*60*1000) > enteredDate.getTime()){
alert();
}
DEMO
I will get the date of birth value dynamically from users visiting to the site, but when the user will insert birthday value I have to check whether the user is 18 years old or not.
user will insert a value like 18/09/2012 as dd/mm/yyyy format.
var arr = date.split("/"); //date is the value of birth date.
var day = arr[0];
var month = arr[1];
var year = arr[2];
How should I do it?
Take a look at the following question, it will help you calculate the age -
Calculate age in JavaScript
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
you may try any of these functions Age Calculation from Date of Birth Using Javascript/Jquery or check this one Calculate age in JavaScript
I am doing validation for Driver's Date of birth, it should be minimum of 18 from the current date.
var Dates = $get('<%=ui_txtDOB.ClientID %>');
var Split = Dates.value.split("/");
if (parseInt(Split[2]) > 1993)
{
alert("DOB year should be less than 1993");
Dates.focus();
return false;
}
I am using this above JavaScript validation for checking a person's DOB above 18, but it is not correct. I need to check with today's date and it should be above 18. How can I compare and check with the current date?
I think a better alternative would be to calculate the age of the user, and use that in your if statement.
See this SO answer on how to do just that:
Calculate age in JavaScript
Try this.
var enteredValue = $get('<%=ui_txtDOB.ClientID %>');;
var enteredAge = getAge(enteredValue.value);
if( enteredAge > 18 ) {
alert("DOB not valid");
enteredValue.focus();
return false;
}
Using this function.
function getAge(DOB) {
var today = new Date();
var birthDate = new Date(DOB);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
Demo here: http://jsfiddle.net/codeandcloud/n33RJ/
<script>
function dobValidate(birth) {
var today = new Date();
var nowyear = today.getFullYear();
var nowmonth = today.getMonth();
var nowday = today.getDate();
var b = document.getElementById('<%=TextBox2.ClientID%>').value;
var birth = new Date(b);
var birthyear = birth.getFullYear();
var birthmonth = birth.getMonth();
var birthday = birth.getDate();
var age = nowyear - birthyear;
var age_month = nowmonth - birthmonth;
var age_day = nowday - birthday;
if (age > 100) {
alert("Age cannot be more than 100 Years.Please enter correct age")
return false;
}
if (age_month < 0 || (age_month == 0 && age_day < 0)) {
age = parseInt(age) - 1;
}
if ((age == 18 && age_month <= 0 && age_day <= 0) || age < 18) {
alert("Age should be more than 18 years.Please enter a valid Date of Birth");
return false;
}
}
</script>
After looking at various methods of doing this, I decided the simplest way was to encode the dates as 8-digit integers. You can then subtract today's code from the DOB code and check if it's greater than or equal to 180000.
function isOverEighteen(year, month, day) {
var now = parseInt(new Date().toISOString().slice(0, 10).replace(/-/g, ''));
var dob = year * 10000 + month * 100 + day * 1; // Coerces strings to integers
return now - dob > 180000;
}
let TODAY = new Date(Date.now());
let EIGHTEEN_YEARS_BACK = new Date(new Date(TODAY).getDate() + "/" + new Date(TODAY).getMonth() + "/" + (new Date(TODAY).getFullYear() - 18));
let USER_INPUT = new Date("2003/12/13");
// Validate Now
let result = EIGHTEEN_YEARS_BACK > USER_INPUT // true if over 18, false if less than 18
I think this is the closest possible way to check.
My approach is to find the date 18 (or any number) years ago from today, then see if that's after (greater) than their dob. By setting all values to date objects it makes the comparison easy.
function is_of_age(dob, age) {
// dates are all converted to date objects
var my_dob = new Date(dob);
var today = new Date();
var max_dob = new Date(today.getFullYear() - age, today.getMonth(), today.getDate());
return max_dob.getTime() > my_dob.getTime();
}
Because the Date object can parse strings in a variety of formats, You don't have to worry too much about where dob is coming from. Simply call is_of_age("1980/12/4", 18); or is_of_age("2005-04-17", 13); or basically any string format or numeric that can be parsed as a Date parameter.
My favourite approach is this one:
var dateOfBirth = new Date("02/23/1900");
// calculate difference between now and the dateOfBirth (in milliseconds)
var differenceMs = Date.now() - dateOfBirth.getTime();
// convert the calculated difference in date format
var dateFromEpoch = new Date(differenceMs);
// extract year from dateFromEpoch
var yearFromEpoch = dateFromEpoch.getUTCFullYear();
// calculate the age of the user
var age = Math.abs(yearFromEpoch - 1970);
console.log("Age of the user: " + age + " years")
You can use the below:
var birthDate = new Date("2018-06-21");
var birthDate1 = new Date("1975-06-21");
function underAgeValidate(birthday) {
const diff = Date.now() - birthday.getTime();
const ageDate = new Date(diff);
let age = Math.abs(ageDate.getUTCFullYear() - 1970);
return age < 18;
};
console.log(underAgeValidate(birthDate));
console.log(underAgeValidate(birthDate1));