【问题标题】:Jquery adding days to a date (abnormal results)jquery给日期加天(结果异常)
【发布时间】:2014-02-09 06:45:13
【问题描述】:

这个问题很常见。我知道,我已经尝试过我在这里找到的解决方案,代码有效,但结果不正常

我正在尝试将天数添加到 15、30、60 等日期 但是为了更好地理解,我得到的结果有几个月的异常变化我在这里有一个 jsfiddle:http://jsfiddle.net/CjEEs/

输入:2014 年 9 月 2 日

添加 15 天后

预期输出:24/02/2014

我得到的输出:03/08/2016

我正在使用的 JavaScript

 var terms = $("#terms").val();
        var date = new Date();
        date.setDate(date.getDate() + terms);
        var day = ("0" + date.getDate()).slice(-2);
        var month = ("0" + (date.getMonth() + 1)).slice(-2);
        var final = date.getFullYear()+"-"+(month)+"-"+(day);
        $("#duedate").val(final);

谢谢!

【问题讨论】:

标签: javascript jquery html date


【解决方案1】:

试试这个:

var terms = 15;
var txt = "09/02/2014";
var sp = "/";
var arr = txt.split(sp);
txt = arr[0];
arr[0] = arr[1];
arr[1] = txt;
txt = arr.join(sp);
var dt = new Date(txt);
console.log(dt);//prints: Date {Sun Feb 09 2014 00:00:00 GMT+0530 (IST)}
dt.setDate(dt.getDate() + terms);
console.log(dt);//prints: Date {Mon Feb 24 2014 00:00:00 GMT+0530 (IST)}

【讨论】:

  • 你可以直接使用 Date 构造函数来解析字符串日期,它接受 MM/dd/yyyy 格式的参数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-22
  • 2015-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-14
相关资源
最近更新 更多