简体   繁体   English

如何在JS日期对象中转换JSON字符串?

[英]How to convert a JSON string in JS date object?

   {"date":"Thu Dec 06 14:56:01 IST 2012"}

我正在获取此字符串,因为JSON可以将其转换为JS日期对象吗?

Edit: Unfortunately i was totally wrong, sry for that,my bad, it happened to always result in today, but to not screw you up, heres an solution which should work for you anyway If you get Different Time strings from your Server, maybe the best way is to write a Regex pattern that matches your String patterns 编辑:不幸的是,我完全错了,很抱歉,我的错,它总是会在今天出现,但是为了不让您陷入困境,这是一个无论如何都应该为您服务的解决方案,如果您从服务器中获得了不同的时间字符串,也许最好的方法是编写与您的String模式匹配的Regex模式

  • Access your date propertie from your JSON Object 从JSON对象访问date属性
  • Since instantiating a Date object with this "Thu Dec 06 14:56:01 IST 2012" String would result in an Invalid Date 由于使用此“ Thu Dec 06 14:56:01 IST 2012”字符串实例化Date对象将导致无效的Date
  • Remove the "IST" myJson.date.replace(" IST","") 删除“ IST” myJson.date.replace(" IST","")
  • Instantiate the your Date object with your new String myDate = new Date("Thu Dec 06 14:56:01 2012") 使用新的字符串myDate = new Date("Thu Dec 06 14:56:01 2012")实例化Date对象。
  • Now theres really your Date Object 现在确实有您的Date对象

var myJson = {"date":"Thu Dec 06 14:56:01 IST 2012"}
var myDate = new Date(myJson.date.replace(" IST",""))
console.log(myDate.toLocaleDateString())

Heres the JSBin 继承人

The right way to convert your JSON to the data object it's parsing this date as a string. 将您的JSON转换为数据对象的正确方法是将日期解析为字符串。

var myJson = {"date":"Thu Dec 06 14:56:01 IST 2013"}
var myDate = new Date(Date(myJson.date))
console.log(myDate.getFullYear()) // 2012

Doesn't work with a Year different from the current one. 不适用于不同于当前年份的年份。

Related link 相关连结
Where can I find documentation on formatting a date in JavaScript? 在哪里可以找到有关在JavaScript中格式化日期的文档?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM