javascript - Convert milliseconds to years -


i have validator checks if user @ least 18 years old.

this check:

        var res = /^([1-2]\d{3})\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])\-([0-9]{4})$/.exec(str);         var todays_date = new date();         var birth_date = null;          if (res != null) {             birth_date = new date(res[1], res[2], res[3]);             if (todays_date - birth_date > 565633905872) { 

565633905872 18 years in milliseconds. how convert years before can do

if (todays_date - birth_date => 18) { 

the number have quoted not number of milliseconds in 18 years. it's small if pretend there no leap years.

the simplest way test if @ least 18 years old initialise date object birthday, use .getfullyear() , .setfullyear() directly set year 18 years forward. compare current date.

note in js dates month zero-based, want use res[2] - 1 when creating date object.

birth_date = new date(res[1], res[2] - 1, res[3]); birth_date.setfullyear(birth_date.getfullyear() + 18); if (birth_date <= new date()) { 

or given constructing birth_date individual year, month , day do:

birthplus18 = new date(+res[1] + 18, res[2] - 1, res[3]); if (birthplus18 <= new date()) { 

(the leading + in +res[1] + 18 not typo, converts string extracted regex number can add 18 it. don't need same thing res[2] - 1 because - automatically converts both operands.)

note regex happily allow dates specify day high month, e.g., feb 30 or jun 31.


Comments