设置datetime-local从Date开始的值 [英] Setting value of datetime-local from Date
问题描述
我想用当前日期和时间设置datetime-local输入的值。现在,我有一个丑陋的解决方案,涉及切片前17个字符。此外,它以格林尼治标准时间设置时间,而不是本地时间。我的代码如下:
I would like to set the value of a datetime-local input with the current date and time. Right now I have an ugly solution that involves slicing the first 17 characters. In addition it sets the time in GMT instead of the local time. My code is as follows:
<input type="datetime-local" name="name" id="1234">
<script type="text/javascript">
var d = new Date();
var elem = document.getElementById("1234");
elem.value = d.toISOString().slice(0,16);
</script>
此代码有两个问题:
- 是否可以将
Date
转换为合法值,而无需手动分割字符串? - 我希望字符串在datetime-local中显示为
DD / MM / YYYY,hh:mm
(例如05/11 / 2015,14:10
在GMT中是13:10
,但是我在GMT + 1中,所以我想显示14:10
)。当前显示的是05/11/2015,01:10 PM
。我想删除PM并在当地时间显示。
- Is there a way to convert from a
Date
to a legal value without manually slicing the string? - I would like the string to be displayed in the datetime-local as
DD/MM/YYYY, hh:mm
(e.g.05/11/2015, 14:10
it is13:10
in GMT but I am in GMT+1 so I want to display14:10
). What is currently displayed is05/11/2015, 01:10 PM
. I would like to remove the PM and display in local time.
这可能是 XY问题,因此,如果我做错了,并且有更好的方法在html中显示日期时间选择器,我会
This might be an XY problem, so if I am doing it completely wrong and there is a better way to display datetime pickers in html, I would be happy to hear.
推荐答案
toISOString
函数负责转换您的本地日期(新日期
)转换为GMT。
The toISOString
function is responsible of converting your local date (new Date
) into GMT.
如果您不想使用GMT,请进行切片,您需要使用纯Date构造函数和所有getX函数,其中X是(天,月,年...)
If you don't want to use GMT then slice, you need to use the pure Date constructor and all of the getX functions, where X is (days, month, year...)
此外,您还需要扩展 Number
对象的功能,该函数将帮助您返回 01
而不是 1
,以保留 dd / mm / yyyy,hh / mm
格式。
In addition, you'll need to extend the Number
object with a function that will help you to return 01
instead of 1
for example, to preserve the dd/mm/yyyy, hh/mm
format.
让我称之为原型函数 AddZero
<input type="datetime-local" name="name" id="1234">
<script type="text/javascript">
Number.prototype.AddZero= function(b,c){
var l= (String(b|| 10).length - String(this).length)+1;
return l> 0? new Array(l).join(c|| '0')+this : this;
}//to add zero to less than 10,
var d = new Date(),
localDateTime= [(d.getMonth()+1).AddZero(),
d.getDate().AddZero(),
d.getFullYear()].join('/') +', ' +
[d.getHours().AddZero(),
d.getMinutes().AddZero()].join(':');
var elem=document.getElementById("1234");
elem.value = localDateTime;
</script>
这篇关于设置datetime-local从Date开始的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!