gpt4 book ai didi

Javascript:输入日期 - 当前日期功能接近但不太正确?

转载 作者:行者123 更新时间:2023-11-29 10:11:54 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,当给定一个过去的日期时,该函数将计算从那时起的年、月和日,以滴流式剩余方式计算。与“2 年 1 个月 3 天”一样,不是所有 3 种格式的总时间(2 年 = 24 个月 = 730 天)。

代码:

    //Function to tell years/months/days since birthday to today
var ageID = function(date){
var nowDate = new Date();

//current date
var nowYear = nowDate.getFullYear();
var nowMonth = nowDate.getMonth();
var nowDay = nowDate.getDay();

//input birthday
var year = date[0];
var month = date[1];
var day = date[2];

var longMonth = [1, 3, 5, 7, 8, 10, 12];
var shortMonth = [4, 6, 9, 11];
var febMonth = [2];
var specfMonth = 0;

//finding month that corresponds to 28, 30, or 31 days in length
for (i = 0; i < longMonth.length; i++){
if (longMonth[i] === month){
specfMonth = 31;
}
}
for (i = 0; i < shortMonth.length; i++){
if (shortMonth[i] === month){
specfMonth = 30;
}
}
for (i = 0; i < febMonth.length; i++){
if (febMonth[i] === month){
specfMonth = 28;
}
}

//Reduced input and current date
var redYear = nowYear - year - 1;
var redMonth = 0;
var redDay = 0;




//The following 2 if/else are to produce positive output instead of neg dates.
if (nowMonth < month){
redMonth = month - nowMonth;
}else{
redMonth = nowMonth - month;
}

if (nowDay < day){
redDay = day - nowDay;
}else{
redDay= nowDay - day;
}

var adjMonth = 12 - redMonth;
var adjDay = specfMonth - redDay;

if (redYear < 1){
return adjMonth + " months, " + adjDay + " days ago.";
}else{
return redYear + " years, " + adjMonth + " months, " + adjDay + " days ago.";
}
};

console.log(ageID([2001, 9, 11]));

输出:13 年 10 个月 20 天前。

然而,准确的输出将是:13 年 10 个月 30 天前。

最佳答案

您的问题是:var nowDay = nowDate.getDay();

您应该改用:nowDate = nowDate.getDate();

getDay() 返回一周中的天数。星期一是“1”,星期二是“2”,依此类推。

关于Javascript:输入日期 - 当前日期功能接近但不太正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31926365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com