如何向用户添加一天's的输入

How can I add a day to user's input?

本文关键字:输入 一天 用户 添加      更新时间:2023-09-26

我有一个文本字段,以这种格式输入日期:yyyy-mm-dd,如何在用户输入的日期中添加一天?我有以下代码,但它不起作用。。。

users_date = document.getElementById('users_date').value;    
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;

第一个问题是第二个问题中的日期格式类似于"2013年8月5日星期一16:24:40 GMT-0500(Hora est.Pacífico,Sudamérica)"

第二个问题是,当用户输入一个月的第一天,如"2013-01-01"或"2013-08-01"时,它会显示"2013年9月1日星期日16:26:06 GMT-0500(Hora est.Pacífico,Sudamérica)"ALWAYS

例如,如果用户输入2013-01-01,我希望另一个文本字段为2013-01-02或2013-08-31,它显示2013-09-01,我该怎么做?

谢谢!!

它不重复,因为其他帖子没有格式化日期

在ES5之前,没有解析日期的标准。现在有一种格式是ISO8601的版本,但并不是所有使用中的浏览器都支持它,而且通常不用于用户输入。

通常会请求一种格式,或者使用返回特定格式的"日期选择器"。从那里,解析字符串以创建Date对象非常简单:

// s is date string in d/m/y format
function stringToDate(s) {
  var b = s.split(/'D/);
  return new Date(b[2], --b[1], b[0]);
}

对于ISO8601格式(y-m-d),只需更改零件的顺序:

// s is date string in y/m/d format
function isoStringToDate(s) {
  var b = s.split(/'D/);
  return new Date(b[0], --b[1], b[2]);
}

要向Date对象添加一天,只需添加一天:

var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);

这应该有效:

var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day
document.getElementById('next_date').value = next_date.getFullYear() + "-" +
                            (next_date.getMonth()++) + "-" + next_date.getDate();

请注意,Date#getMonth()是基于零的。因此,增量。