Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取用户';以年计的年龄_Javascript_Date_Browser_Geolocation_Ecma - Fatal编程技术网

Javascript 如何获取用户';以年计的年龄

Javascript 如何获取用户';以年计的年龄,javascript,date,browser,geolocation,ecma,Javascript,Date,Browser,Geolocation,Ecma,我想在JavaScript(ECMA)中使用Geolocation和Date,询问用户出生地点和时间,并将其转换为年份。我问他们出生在哪里,因为我需要考虑不同的时区 到目前为止,my函数返回用户的年龄: function birth() { var their_birth_day = new Date("18 May 2005"); // Just as an example var today = new Date(); var ms_old = today.

我想在JavaScript(ECMA)中使用
Geolocation
Date
,询问用户出生地点和时间,并将其转换为年份。我问他们出生在哪里,因为我需要考虑不同的时区

到目前为止,my函数返回用户的年龄:

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;
}
但是如何使用它们的位置使其更精确呢?

函数getAge(dateString){
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;
}
var today=新日期(); var birthDate=新日期(日期字符串); var age=today.getFullYear()-birthDate.getFullYear(); var m=today.getMonth()-birthDate.getMonth(); 如果(m<0 | |(m==0&&today.getDate()
你能解释更多吗?请告诉我什么是古老的表达方式为什么你需要地理定位API来获取用户出生地?你提到了时区,你可以使用Date().getTimezoneOffset()@Tunjay也许我没有,我只是需要一种方法来消除时区差异,使我的yrs_old变量不精确。@me.nkr yrs_old是用户生日和今天之间的时间量,以年为单位。换句话说,用户的年龄。我没有把它四舍五入,但我会把它四舍五入到小数点后3位(但忽略这一点,因为这对这个问题并不重要)。