我正在嘗試使用D3.js計算個人的年齡。我有以下代碼:
d3.timeYear.count(Birth_date, Current_date);
Birth_date 是個人的出生日期(一個 Date 物件),而 Current_date 是我想計算個人年齡的日期。能夠回答“如果您出生于 1975 年 5 月 5 日,那么您在 1976 年 5 月 3 日時多大”。
d3.timeYear.count()似乎將日期設定為年初,因此在我的示例中,我的代碼將1在 1976 年 1 月 1 日回傳,即使這個人距離他的第一個生日還有 5 個月的時間。
我可以計算天數而不是年數,但是根據一年中的天數,我可能會在本地得到錯誤的結果。
uj5u.com熱心網友回復:
以下基于 JavaScript Date 物件,應該可以完成這項作業:
function age(by,bm,bd){
const D=new Date(), y=D.getFullYear(),
md=D.getMonth()-bm, dd=D.getDate()-bd;
return y-by-(md>0||!md&&dd>=0?0:1);
}
console.log(age(1992,8,26))
基本上我會回傳今天全年和生日之間的差異。但我也檢查當前月份是否大于生日月份或 ( ||) 如果月差為零 ( !mdis true) 并且 ( &&) 日差dd大于零。如果是這種情況,我0會1從年差中減去。
請注意,我的age()函式希望以 JavaScript 表示法輸入月份。這意味著8在上面的示例中是指 9 月份。
uj5u.com熱心網友回復:
Carsten Massman 的回答啟發了我制作這個功能,它解決了我的問題:
function age(birthdate, currentdate){
const bDay = birthdate.getDate(); // Get the birthdate's day.
const bMonth = birthdate.getMonth(); // Get the birthdate's month.
const currYear = currentdate.getFullYear(); // Get the current date's year.
const currBirthday = new Date(currYear "/" (bMonth 1) "/" bDay); // Contruct the date of the birthday in the current year
const daysToBirthday = d3.timeDay.count( d3.timeYear.floor(currBirthday), currBirthday); // Count the # of days since Jan. 1st this year
// Offset the current date in the past by the number of days computed above.
const offsetCurrent = d3.timeDay.offset(currentdate, -daysToBirthday);
// Compute the number of years between the two dates (floored to the beginning of their respective year).
return d3.timeYear.count(birthdate, offsetCurrent);
}
這計算任何出生日期的年齡,以及之后的任何時間點,主要使用 d3-time 和一點香草 javascript 的 Date 方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513939.html
