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

查看:28
本文介绍了如何从 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);

我也尝试了以下代码来弥补它,但它也不总是正确的

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天全站免登陆