简体   繁体   中英

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

  • Access your date propertie from your JSON Object
  • Since instantiating a Date object with this "Thu Dec 06 14:56:01 IST 2012" String would result in an Invalid Date
  • Remove the "IST" myJson.date.replace(" IST","")
  • Instantiate the your Date object with your new String myDate = new Date("Thu Dec 06 14:56:01 2012")
  • Now theres really your Date Object

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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