【问题标题】:How to get tomorrow's date of a specific date如何获取特定日期的明天日期
【发布时间】:2021-08-21 07:52:35
【问题描述】:

我正在尝试使用 JavaScript 格式 (yyyy-mm-dd) 获取特定日期的明天日期。例如具体日期是2021-08-31,我有这个脚本:

var date  = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1],date.split("-")[2]) 
date.setDate(date.getDate() + 1);
var tomorrows_date_month = date.getMonth()
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)

预期的输出是:

2021-09-01

但是这段代码的输出是:

2021-9-2

【问题讨论】:

标签: javascript


【解决方案1】:

首先您不需要拆分"2021-08-31" 来用作date 参数,所以只需使用new Date("2021-08-31");

第二个注意,如果长度小于2,则需要使用d.getMonth() + 1并加上前导零:

试试这个:

function formatDate(date) {
    var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2) 
        month = '0' + month;
    if (day.length < 2) 
        day = '0' + day;

    return [year, month, day].join('-');
}

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date  = "2021-08-31"

var date1 = new Date(date);

console.log(formatDate(date1.addDays(1)));

【讨论】:

    【解决方案2】:

    内部js月份存储为0到11之间的值。所以你需要将date.split("-")[1]减1。否则,javascript会认为你的月份实际上是9月,我们知道“2021-09-32”是翻译为“2021-10-2”,因此日期显示为“2”。

    var date  = "2021-08-31"
    date = new Date(date.split("-")[0],date.split("-")[1] - 1,date.split("-")[2]) 
    date.setDate(date.getDate() + 1)
    var tomorrows_date_month = date.getMonth() + 1
    var tomorrows_date_day = date.getDate()
    var tomorrows_date_year = date.getFullYear()
    console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
    

    还要注意date = new Date("2021-08-31") 足以将字符串转换为Date 对象。

    【讨论】:

      【解决方案3】:
      new Date(new Date(date + 'T00:00Z').getTime() + 86400000).toISOString().substr(0, 10)
      

      添加的'T00:00Z' 确保日期被解析为UTC,以匹配toISOString() 使用的UTC 时区。加上 86400000(一天的毫秒数)提前了日期,而不必直接对日期字段大惊小怪。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 2020-10-27
        • 1970-01-01
        相关资源
        最近更新 更多