使用 Javascript 预填充日期输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14245339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pre-populating date input field with Javascript
提问by MyTimeFinder
I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:
我试图将日期预填充到 html“日期”输入字段中,但它忽略了我尝试传递的值:
<html>
...
<input id='date' type='date'>
...
</html>
<script>
...
var myDate = new Date();
$("#date").val(myDate);
...
I have also tried passing the date object as a string
我也试过将日期对象作为字符串传递
var myDate = new Date().toDateString();
$("#date").val(myDate);
When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.
当我打开表单时,日期字段是空白的。如果我消除了 type="date" 标记,该值将显示为一个字符串,但是我无权访问日期选择器。如何预先填充日期输入并仍然使用日期选择器?我难住了。
Thanks.
谢谢。
回答by Robin Drexler
It must be set in ISO-format.
它必须以 ISO 格式设置。
(function () {
var date = new Date().toISOString().substring(0, 10),
field = document.querySelector('#date');
field.value = date;
console.log(field.value);
})()
回答by MyTimeFinder
Thank you j08691. That link was the answer.
谢谢j08691。那个链接就是答案。
To others struggling like me, when they say input is "yyyy-mm-dd" the MEAN it!
对于像我这样挣扎的人,当他们说输入是“yyyy-mm-dd”时,意思是它!
You MUST have 4 digits for the year. You MUST have a dash and no spaces. You MUST have 2 digits for day and month.
年份必须有 4 位数字。你必须有一个破折号,没有空格。您必须有 2 位数字表示日和月。
In my example myDate.getMonth for January would only return "1" (actually it returns "0" because for some reason javascript counts months from 0-11). To get this right I had to do the following:
在我的示例中,一月的 myDate.getMonth 只会返回“1”(实际上它返回“0”,因为出于某种原因,javascript 从 0 到 11 计算月份)。为了做到这一点,我必须执行以下操作:
var myDate, day, month, year, date;
myDate = new Date();
day = myDate.getDate();
if (day <10)
day = "0" + day;
month = myDate.getMonth() + 1;
if (month < 10)
month = "0" + month;
year = myDate.getYear();
date = year + "-" + month + "-" + day;
$("#date").val(date);
I hope this helps others not waste hours like I did testing this before October or before the 10th of the month! LOL
我希望这可以帮助其他人不要像我在 10 月之前或本月 10 日之前所做的那样浪费时间!哈哈
回答by mattbell87
Here is an answer based on Robin Drexlersbut in local time.
这是基于Robin Drexlers但在当地时间的答案。
//Get the local date in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 10);
//Set the field value
var field = document.querySelector('#date');
field.value = datestr;
If it's a datetime field you're modifying (as opposed to just the date) don't forget to add the time T00:00, or change the substring to 16 characters for example:
如果它是您正在修改的日期时间字段(而不仅仅是日期),请不要忘记添加时间T00:00,或将子字符串更改为 16 个字符,例如:
//Get the local date and time in ISO format
var date = new Date();
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
var datestr = date.toISOString().substring(0, 16);
//Set the field value
var field = document.querySelector('#datetime');
field.value = datestr;
回答by sanath_p
This below code populates the local date . The accepted answer populates UTC date.
下面的代码填充本地日期。接受的答案填充 UTC 日期。
var date = new Date();
field = document.querySelector('#date-id');
var day = date.getDate();
if(day<10){ day="0"+day;}
var month = date.getMonth()+1;
if(month<10){ month="0"+month;}
field.value = date.getFullYear()+"-"+month+"-"+day;
回答by gwelter
Why Not to Use toISOString()
为什么不使用 toISOString()
The <input type='date'>field takes a value in ISO8601 format (reference), but you should not use the Date.prototype.toISOString()function for its value because, before outputting an ISO8601 string, it converts/represents the date/time to UTC standard time (read: changes the time zone) (reference). Unless you happen to be working in or want that time standard, you will introduce a bug where your date will sometimes, but not always, change.
该<input type='date'>字段采用 ISO8601 格式的值(参考),但您不应使用该Date.prototype.toISOString()函数作为其值,因为在输出 ISO8601 字符串之前,它会将日期/时间转换/表示为 UTC 标准时间(读取:更改时区) (参考)。除非你碰巧在工作或想要那个时间标准,否则你会引入一个错误,你的日期有时会改变,但并非总是如此。
Populate HTML5 Date Input from Date Object w/o Time Zone Change
从没有时区更改的日期对象填充 HTML5 日期输入
The only reliable way to get a proper input value for <input type='date'>without messing with the time zone that I've seen is to manually use the date component getters:
获得正确输入值的唯一可靠方法<input type='date'>是手动使用日期组件获取器:
let d = new Date();
let datestring = d.getFullYear().toString() + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
document.getElementById('date').value = datestring;
/* Or if you want to use jQuery...
$('#date').val(datestring);
*/
<input id='date' type='date'>
Populate HTML5 Date & Time Fields from Date Object w/o Time Zone Change
从不更改时区的日期对象填充 HTML5 日期和时间字段
This is beyond the scope of the original question, but for anyone wanting to populate both date & time HTML5 input fields from a Date object, here is what I came up with:
这超出了原始问题的范围,但对于想要从 Date 对象填充日期和时间 HTML5 输入字段的任何人,这就是我想出的:
// Returns a 2-member array with date & time strings that can be provided to an
// HTML5 input form field of type date & time respectively. Format will be
// ['2020-12-15', '01:27:36'].
function getHTML5DateTimeStringsFromDate(d) {
// Date string
let ds = d.getFullYear().toString() + '-' + (d.getMonth()+1).toString().padStart(2, '0') + '-' + d.getDate().toString().padStart(2, '0');
// Time string
let ts = d.getHours().toString().padStart(2, '0') + ':' + d.getMinutes().toString().padStart(2, '0') + ':' + d.getSeconds().toString().padStart(2, '0');
// Return them in array
return [ds, ts];
}
// Date object
let d = new Date();
// Get HTML5-ready value strings
let dstrings = getHTML5DateTimeStringsFromDate(d);
// Populate date & time field values
document.getElementById('date').value = dstrings[0]
document.getElementById('time').value = dstrings[1]
/* Or if you want to use jQuery...
$('#date').val(dstrings[0]);
$('#time').val(dstrings[1]);
*/
<input type='date' id='date'>
<input type='time' id='time' step="1">
回答by Laura
I don't have the reputation points to comment on another answer, so I'll just add a new answer. And since I'm adding an answer, I'll give more details than I would've in a comment.
我没有声誉点来评论另一个答案,所以我只会添加一个新答案。由于我正在添加答案,因此我将提供比评论中更多的细节。
There's an easier way to zero pad than all of the juggling that everyone is doing here.
有一种比每个人都在这里做的所有杂耍更简单的零垫方法。
var date = new Date();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
var year = date.getFullYear();
var htmlDate = year + '-' + month + '-' + day;
console.log("Date: " + htmlDate);
Today, the output would be
今天,输出将是
Date: 2020-01-07
The code is building a dynamic string by prepending a quoted zero, then taking the last 2 characters with slice(-2). This way, if the zero makes it 01, the last 2 are 01. If the zero makes it 011, then the last two are 11.
代码通过在前面加上带引号的零来构建动态字符串,然后使用 slice(-2) 取最后 2 个字符。这样,如果零使它成为 01,那么最后 2 个就是 01。如果零使它成为 011,那么最后两个就是 11。
As for the month starting at zero silliness, you can also add 1 dynamically before prepending the zero and everything still works. You just have to do the math operation before turning it into a string.
至于从零开始的月份,您还可以在添加零之前动态添加 1,一切仍然有效。您只需要在将其转换为字符串之前进行数学运算。
As a side note, I've noticed that when you update a date field, you have to hide the field before setting the value and show it after setting. I don't do this often enough, so I have to re-struggle each time I need to deal with it. Hopefully this will help someone from the future.
作为旁注,我注意到当您更新日期字段时,您必须在设置值之前隐藏该字段并在设置后显示它。我不经常这样做,所以每次我需要处理它时我都必须重新挣扎。希望这会对未来的人有所帮助。
waves to future people
向未来的人们挥手致意

