1

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)}
RobG
  • 142,382
  • 31
  • 172
  • 209
OMGGItsRob
  • 11
  • 3
  • You don't want milliseconds, you want the date difference in years, see [*Calculate age given the birth date in the format YYYYMMDD*](https://stackoverflow.com/questions/4060004/calculate-age-given-the-birth-date-in-the-format-yyyymmdd). – RobG Mar 14 '21 at 22:33

2 Answers2

-1

You can create a new Date object and call getTime() on it to get the unix timestamp.

date = new Date('2020-01-01')
// Wed Jan 01 2020 07:00:00 GMT+0700 (Indochina Time)
date.getTime()
// 1577836800000

Let's say your definition of an "adult" is that someone has to be at least 18 years old. 18 years is 568036800000 milliseconds (assuming 365.25 days per year). Then, your check function would be as follow:

const ADULT_THRESHOLD_MILLISECONDS = 568036800000;

function checkIsAdult(patientDob) {
  const patientDobUnixTimestamp = new Date(patientDob).getTime();
  const currentTimestamp = Date.now();

  return (currentTimestamp - patientDobUnixTimestamp) > ADULT_THRESHOLD_MILLISECONDS;
}
Jackyef
  • 4,734
  • 18
  • 26
  • '2020-01-01' is parsed as UTC whereas the OP likely wants local, so you start with an incorrect time value. 568036800000 represents 1 Jan 1988 (UTC), which is 32 years before 1 Jan 2020, not 18. To test for someone to be at least 18 on that date, the comparison date should be 1 Jan 1998. – RobG Mar 14 '21 at 22:42
-1

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

Isaac Yong
  • 109
  • 1
  • 5
  • There are [many questions on calculating age](https://stackoverflow.com/search?q=%5Bjavascript%5D+get+age) that have better answers. `new Date(\`${month} ${day}, ${year}\`)` produces an invalid date in Safari. – RobG Mar 14 '21 at 22:45