计算两个日期之间的天数精确到 .5?

想计算两个日期之间相差的天数,还要根据时间精确到半天。比如2023-01-12 8:00~2023-01-12 12:00,算0.5天;比如2023-01-12 8:00~2023-01.13 12:00,算1.5天。这种要怎么算?

阅读 1.7k
4 个回答

看了下你的描述,你想要的是这样一个效果?

function getDays(startDate,endDate) {
    var days = 0;
    var startInfo = startDate.split(' '),
        endInfo = endDate.split(' '),
        
        startDay = new Date(startInfo[0]),
        endDay = new Date(endInfo[0]), 
        
        endHour = endInfo[1].split(':')[0]
    
    if( startDay.getTime() != endDay.getTime()) {
        days = (endDay.getTime() - startDay.getTime()) / 86400000
    }

    if(endHour <= 12) {
        days += 0.5
    } else {
        days += 1
    }
    return days
}

转换为时间戳,精确到毫秒都行

最后这样写的

function DateDiff(sDate1: any, sDate2: any) {    //sDate1和sDate2是2022-12-18格式
    var aDate, oDate1, oDate2, iDays
    aDate = sDate1.split("-")
    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])    //转换为12-18-2022格式
    aDate = sDate2.split("-")
    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0])
    //@ts-ignore
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24)    //把相差的毫秒数转换为天数
    return iDays
}
//将时分秒转为时间戳
function time_to_sec(time: any) {
    if (time !== null) {
        var s = "";
        var hour = time.split(":")[0];
        var min = time.split(":")[1];
        //@ts-ignore
        s = Number(hour * 3600) + Number(min * 60);
        // console.log(hour, 'console.log(hour);');
        return s;
    }
}

const comdays = () => {
    let times = DateDiff(startdate.value, enddate.value)
    // console.log(times);
    //@ts-ignore
    if (time_to_sec(endtime.value) <= time_to_sec('12:00')) {
        //@ts-ignore
        formData.value.day = times + 0.5
    } else {
        //@ts-ignore
        formData.value.day = times + 1
    }

}

你这个半天的逻辑怎么算的,按工作时间算么?还有你这个一天的逻辑是不是也按照工作逻辑算

推荐问题
宣传栏