从给定的字符串格式计算 DOB
Calculate DOB from a given string format
以下是我的日期时间。我需要计算给定出生日期的年龄(以年为单位)和天数。
出生日期格式如下
Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)
代码
CalculateAge (dob :string) : string {
if (dob === null) return "age";
let [year, month, day] = dob.split('-').map(Number);
month -=1;
const ag = Date.now() - new Date(year, month, day).getTime();
const ad = new Date(ag);
return Math.abs(ad.getUTCFullYear() - 1970).toString();
}
我得到的输出是 NaN。如何通过从日期获取正确的 DOB 来解决此问题?
这是将日期字符串转换为 yyyy-mm-dd 格式的方法。
convertDateString(str :string) : string {
let date = new Date(str);
mnth = ("0" + (date.getMonth() + 1)).slice(-2);
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
console.log(convertDateString("Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)"))
//-> "2021-07-13"
您可以使用以下函数计算年龄
calculateAge() {
let birthday = convertDateString("Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)");
let ageDifferentMs = Date.now() - new Date(birthday).getTime();
let ageDate = new Date(ageDifferentMs ); // epoch miliseconds
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
以下是我的日期时间。我需要计算给定出生日期的年龄(以年为单位)和天数。
出生日期格式如下
Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)
代码
CalculateAge (dob :string) : string {
if (dob === null) return "age";
let [year, month, day] = dob.split('-').map(Number);
month -=1;
const ag = Date.now() - new Date(year, month, day).getTime();
const ad = new Date(ag);
return Math.abs(ad.getUTCFullYear() - 1970).toString();
}
我得到的输出是 NaN。如何通过从日期获取正确的 DOB 来解决此问题?
这是将日期字符串转换为 yyyy-mm-dd 格式的方法。
convertDateString(str :string) : string {
let date = new Date(str);
mnth = ("0" + (date.getMonth() + 1)).slice(-2);
day = ("0" + date.getDate()).slice(-2);
return [date.getFullYear(), mnth, day].join("-");
}
console.log(convertDateString("Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)"))
//-> "2021-07-13"
您可以使用以下函数计算年龄
calculateAge() {
let birthday = convertDateString("Thu Jul 13 2021 19:10:53 GMT+0530 (India Standard Time)");
let ageDifferentMs = Date.now() - new Date(birthday).getTime();
let ageDate = new Date(ageDifferentMs ); // epoch miliseconds
return Math.abs(ageDate.getUTCFullYear() - 1970);
}