Javascript 在javascript中设置输入类型日期和时间的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28729634/
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
Set values in input type date and time in javascript
提问by DOM manipulator
I have 2 input fields :
我有 2 个输入字段:
Date:
日期:
<input type="date" id="currentDate">
Time:
时间:
<input type="time" id="currentTime" >
I'm just testing those new features of html5. How to set current values in these fields. I am having a hard time setting values in those fields through javascript.
我只是在测试 html5 的那些新功能。如何在这些字段中设置当前值。我很难通过 javascript 在这些字段中设置值。
回答by jungy
You can just set the valueof the input field with the respective formats:
您可以value使用相应的格式设置输入字段的 :
dateis yyyy-MM-dd
date是 yyyy-MM-dd
timeis HH:mm
time是 HH:mm
Using your example, you can do something simple like:
使用您的示例,您可以执行以下简单操作:
var date = new Date();
var currentDate = date.toISOString().slice(0,10);
var currentTime = date.getHours() + ':' + date.getMinutes();
document.getElementById('currentDate').value = currentDate;
document.getElementById('currentTime').value = currentTime;
回答by XepherX
var date = new Date();
var day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
min = date.getMinutes();
month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
var today = year + "-" + month + "-" + day,
displayTime = hour + ":" + min;
document.getElementById('formdate').value = today;
document.getElementById("formtime").value = displayTime;
回答by Tech1337
I find that using ISOString, the format is, of course, standardised. You can simply split the string at 'T' for an array of date and time (Zulu included, you may wish to splice out the last char, 'Z').
我发现使用 ISOString,格式当然是标准化的。您可以简单地将字符串在 'T' 处拆分为日期和时间数组(包括祖鲁语,您可能希望拼接出最后一个字符 'Z')。
Thus, the simplest solution I found was merely to:
因此,我找到的最简单的解决方案只是:
let tmp = new Date(Date.now());
// tmp now like: "2018-08-21T11:54:50.580Z"
let dateInputFormatted = tmp.toISOString().split('T')[0];
// 0, as split produces: ["2018-08-21", "11:54:50.580Z"]
console.log(dateInputFormatted);
回答by Hchab
You can make two prototypes in order to reuse them:
您可以制作两个原型以重复使用它们:
Date.prototype.dateToInput = function(){
return this.getFullYear() + '-' + ('0' + (this.getMonth() + 1)).substr(-2,2) + '-' + ('0' + this.getDate()).substr(-2,2);
}
Date.prototype.timeToInput = function(){
return ('0' + (this.getHours())).substr(-2,2) + ':' + ('0' + this.getMinutes()).substr(-2,2);
}
Then use them like this:
然后像这样使用它们:
var date = new Date();
document.getElementById('currentDate').value = date.dateToInput();
document.getElementById('currentTime').value = date.timeToInput();
回答by keiohtani
var date = new Date();
var dateOptions = { day: '2-digit', month: '2-digit', year: 'numeric' };
var currentDate = date.toLocaleDateString('ja-JP', dateOptions).replace(/\//gi, '-');
var timeOptions = { hour: '2-digit', minute: '2-digit' };
var currentTime = date.toLocaleTimeString('it-IT', timeOptions);
document.getElementById('currentDate').value = currentDate;
document.getElementById('currentTime').value = currentTime;
回答by nash11
In order to convert a date to an ISO date without the time, you need to use the getDate, getMonth, etc. methods instead of getting the ISOStringdirectly and manipulating the string. The latter will not take the timezone into consideration which will lead to unexpected results.
为了一个日期转换为ISO日期没有的时候,你需要使用getDate,getMonth等方法,而不是获取ISOString直接和操纵的字符串。后者不会考虑时区,这将导致意外结果。
Here is a solution for the same using ES6.
这是使用 ES6 的相同解决方案。
// Function which returns a minimum of two digits in case the value is less than 10
const getTwoDigits = (value) => value < 10 ? `0${value}` : value;
const formatDate = (date) => {
const day = getTwoDigits(date.getDate());
const month = getTwoDigits(date.getMonth() + 1); // add 1 since getMonth returns 0-11 for the months
const year = date.getFullYear();
return `${year}-${month}-${day}`;
}
const formatTime = (date) => {
const hours = getTwoDigits(date.getHours());
const mins = getTwoDigits(date.getMinutes());
return `${hours}:${mins}`;
}
const date = new Date();
document.getElementById('currentDate').value = formatDate(date);
document.getElementById('currentTime').value = formatTime(date);
<input type="date" id="currentDate">
<input type="time" id="currentTime">
This will now return the current date and time as per the current timezone.
这将根据当前时区返回当前日期和时间。
回答by Mister Jojo
On modern browsers, this is very simple:
在现代浏览器上,这很简单:
just use HTML_element .valueAsDateinstead of HTML_element .value
只需使用 HTML_element .valueAsDate而不是 HTML_element .value
// just my preference to access form elements by names
const myForm = document.querySelector('#my-Form')
// 1: get local date and time values
let sysDate = new Date()
, userDate = new Date(Date.UTC(sysDate.getFullYear(), sysDate.getMonth(), sysDate.getDate(), sysDate.getHours(), sysDate.getMinutes(), 0));
// 2: set interface values !
myForm.currentDate.valueAsDate = userDate
myForm.currentTime.valueAsDate = userDate
<form action="xxx" id="my-Form">
<input type="date" name="currentDate">
<br><br>
<input type="time" name="currentTime">
</form>
Seconds & Milliseconds infos must be set to zero for currentTime element
对于 currentTime 元素,秒和毫秒信息必须设置为零
userDate.setSeconds(0)
userDate.setMilliseconds(0)

