简体   繁体   中英

How to calculate age from DOB if month is invalid?

I have a date field which accepts if the month is unknown . And I calculate the age from the date entered and the current date and time.

 var birthDate = new Date("12 UNK 1995"); var now = new Date(); var age = now.getFullYear() - birthDate.getFullYear(); document.write("Your Age is: " + age); 

If the run this is throwing me NaN error. I think it is because of that invalid date format.

Is there any way that I can calculate the age even if the month is unknown based on the year only in any kind of date formate?

If the month is unknown then the normal way programmatically to set it to the middle of the year – to July. I know this problem in India – some people do not know their birth date sometimes.

For example like follows:

 var month = "UNK"; // TODO: here is your code to get the month name from field month = month == "UNK" ? "JUL" : month; var birthDate = new Date("12 " + month + " 1995"); var now = new Date(); var age = now.getFullYear() - birthDate.getFullYear(); document.write("Your Age is: " + age); 

But note that your calculation is not really correct because you do not calculate with full date (day, month, year, hour, minutes).

My suggestion

But I would like to suggest to use a new HTML5 input field type date (see this link) which looks like follows (go with mouse pointer over this field):

 <input name="birthdate" type="date" required> 

And all users have to put in this date on their's own accountability. In this case they have to choose one date and you will do not have the accountability for this.

您已经在字符串中输入了年份,因此请从字符串中提取年份,然后从年份中减去。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM