如何从HTML5日期输入中解析日期? [英] How do you parse a date from an HTML5 date input?

查看:129
本文介绍了如何从HTML5日期输入中解析日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网页上输入了一个输入,我可以通过获取ISO字符串和拉出前10个字符来设置日期。

I have an input on my webpage that I am able to set the date on by getting an ISO string and pulling out the first 10 characters.

date = new Date();
dateInput.value = date.toISOString().substr(0,10);

这样做完美。我的问题是,当我试图让日期退出。我得到一天的日期。

This works perfectly. My problem is that when I try to get the date back out. I am getting the date one day off.

var newDate = new Date(dateInput.value);

我也尝试过以下代码来弥补,但是并不总是正确的/ p>

I have also tried the following code to make up for it, but it is not always correct either


新日期(Date.parse(element.value)+ 86400000)

new Date(Date.parse(element.value) + 86400000)

所以我的问题是:是否有一个优雅的方式来保持正确的日期。我一直在寻找一段时间,但是在Javascript中,日期解析似乎并没有太多的一致性。

So my question is: Is there an elegant way to get the correct date consistently. I have been looking around for a little while, but it seems there is not a lot of consistency with date parsing in Javascript.

推荐答案

它将日期解释为UTC,对于大多数时区而言,它将使其看起来像昨天。一个解决方案可能是将时区偏移添加到日期以将其转换为您当地的时区。

It's interpreting the date as UTC, which, for most time zones, will make it seem like "yesterday". One solution could be to add the time-zone offset back into the date to "convert" it to your local timezone.

这篇关于如何从HTML5日期输入中解析日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆