Check age using Date object in JS Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Check age using Date object in JS without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need help with the Date object in JS. I need a return that checks if the patient is an adult based on the DOB. I am unsure how to go about using the date object to get a return of age in milliseconds (Date returns milliseconds since 1 January 1970 UTC). If anyone has an idea, I appreciate it. <3

 let today = Date.now()
 function patient(fname, lname, origin, dob){
    this.fname,
    this.lname,
    this.origin,
    **this.dob,**
    this.age = (today - dob)
    this.isAdult = age > 18)}

Answer

You can convert your DOB to milliseconds since Epoch time with getTime()

for dob, you can set the input variables to be month, day, and year, make a new Date object, and use getTime() to convert it to milliseconds:

 function patient(fname, lname, origin, month, date, year){
    this.fname,
    this.lname,
    this.origin,
    this.dob = new Date(`${month} ${day}, ${year}`).getTime()
    this.age = (Date.now() - dob)/1000/60/60/24/365 
    //convert to seconds/minutes/hours/day/year (ignoring leap years for this examples)
    this.isAdult = age > 18)}

Link to CodePen example

Now it’s just a matter to convert milliseconds back to year, the example above ignores the leap year, depending on the accuracies you going for you can round it up, or write a function to determine the exact numbers down to decimals

We are here to answer your question about Check age using Date object in JS - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji