比较两个日期并以正确的格式返回

Comparing two Dates and returning in correct format

本文关键字:返回 格式 日期 两个 比较      更新时间:2024-02-05

我有一个要求,我需要比较两个日期值(过去日期和现在日期),并以年/月/天为单位返回确切的差异,如果它超过59岁,6个月甚至一天,那么它应该随着年龄的增长而返回,否则就低于年龄

我在网上搜索,但没有得到任何相关的信息。

目前我正在尝试:

var start_date = new Date("1990-04-25");
    var end_date = new Date();
    var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());       
    if (total_months < 714) {
        alert("under age")
    } else { alert("over age") }

我将年份转换为月份,但这并没有给我确切的结果。

有人能帮我解决这个问题吗。

var start_date = new Date("1990-04-25");
    var end_date = new Date();
    var millisec = Math.abs(end_date - start_date); // it will provide you miliseconds
// here you can convert it to days or month and check for over or under age
e.g 
        var seconds = (millisec / 1000).toFixed(1);
        var minutes = (millisec / (1000 * 60)).toFixed(1);
    var hours = (millisec / (1000 * 60 * 60)).toFixed(1);
    var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);

有关更多帮助,请参阅以下内容:1.如何在javascript中减去日期/时间?2.将以秒为单位的时间间隔转换为更便于人类阅读的形式