Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何向用户';谁的输入?_Javascript - Fatal编程技术网

Javascript 如何向用户';谁的输入?

Javascript 如何向用户';谁的输入?,javascript,Javascript,我有一个文本字段,它以这种格式输入日期: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

我有一个文本字段,它以这种格式输入日期: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;
第一个问题是第二个日期的格式类似于“Mon Aug 05 2013 16:24:40 GMT-0500(Hora est.Pacífico,Sudamérica)”

第二个问题是,当用户输入每月的第一天,如“2013-01-01”或“2013-08-01”,它总是显示“Sun Sep 01 2013 16:26:06 GMT-0500(Hora est.Pacífico,Sudamérica)”

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

谢谢


它不会重复,因为另一篇文章没有格式化日期

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

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

// 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]);
}
要向日期对象添加一天,只需添加一天:

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()
是以零为基础的。因此,增量。

在处理日期时,请使用moment.js。不要再掉头发了。请看下面的帖子:希望对你有帮助。是的,moment.js是解决这个问题的最佳方案!!