问题描述
限时送ChatGPT账号..我想将日期解析为 javascript 日期对象.我正在使用以下
I want to parse a date into a javascript date object. I am using the following
new Date(Date.parse('2012-08-01'))
问题是我的输入日期可以是多种格式,解析它应该总是给我日期为日期的日期对象
The problem is my input date can be in multiple formats and parsing it should always give me the date object with the date as
2012-08-01 00:00:00
在当地时区.
在不使用任何第三方库的情况下,javascript 中有哪些可能的选项?
What are possible options in javascript without using any third party libraries ?
我有一个可能的解决方案.但我担心的是我是否应该担心这在某些 android/iphone/kindle/surface 原生浏览器中不起作用?
I have a possible solution. But my concern is should i be worried that this will not work in certain android/iphone/kindle/surface native browsers?
var timezone = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1];
var dateObject = new Date(Date.parse('2012-08-01 '+timezone));
推荐答案
用正斜杠替换破折号,它将使用本地时间.如果您希望它在任何地方都可以使用,请务必使用 yyyy/mm/dd
排序.
Replace the dashes with forward slashes and it will use the local time. Be sure to use yyyy/mm/dd
ordering if you want it to work everywhere.
您也不需要显式调用 Date.parse
.Date
构造函数将在您传递字符串时执行此操作.
You also do not need to explicitly call Date.parse
. The Date
constructor will do that when you pass a string.
new Date('2012/08/01') // local
new Date('2012-08-01') // UTC
是的,JavaScript 很奇怪.
Yes, JavaScript is weird.
这篇关于使用localtimezone解析日期到javascript中的日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论