简体   繁体   English

Json.Stringify搞砸了我的约会对象

[英]Json.Stringify messed up my date object

I have this variable 'previousDate' and assigned it to previous date. 我有此变量“ previousDate”,并将其分配给上一个日期。

var previousDate;

When i do a console.log(previousDate), i get this value at the console. 当我执行console.log(previousDate)时,我会在控制台上获得此值。

Wed Dec 07 2016 10:02:37 GMT-0800 (Pacific Standard Time)

Now, when i json.stringify this data, i get following date and time. 现在,当我json.stringify此数据时,我得到以下日期和时间。

2016-12-07T18:02:37.223Z

The date is the same but please note the time here. 日期是相同的,但请在此处注明时间。 Instead of PST, it is showing me GMT. 而不是PST,它向我显示了GMT。 I need to have the PST timing here too when i stringify. 当我进行字符串化时,我也需要在这里设置PST时间。 Any suggestions please ? 有什么建议吗?

When you create your object, create a method to return a date string. 创建对象时,请创建一个返回日期字符串的方法。
Sample: 样品:

var obj = { d1: (new Date()), d1String: function() { return this.d1.toString(); } }

Or save the YourDate.toString() in one property of your object. 或将YourDate.toString()保存在对象的一个​​属性中。

var objDate = { dateString: YourDate.toString() ;}

Or 要么

var ff = function(YourObject) {  var OBJ = {} ;
for(x in YourObject)
{
   if (typeof(YourObject[x]) !== "function")
       eval("OBJ." + x + " = '" + YourObject[x] + "'");
    else
      eval("OBJ." + x + " = '" + YourObject[x]() + "'");
}
var strOBJ = JSON.stringify(OBJ);
return strOBJ;
}

My Gist on GitHub GitHub上的My Gist

https://gist.github.com/kiaratto/afb6bb9acd21d0dda37157eb3a92ec2f https://gist.github.com/kiaratto/afb6bb9acd21d0dda37157eb3a92ec2f

JavaScript date values don't contain timezone information. JavaScript日期值不包含时区信息。

When you log something to the console, the browser does its best to show you relevant and useful information. 当您将某些内容登录到控制台时,浏览器会尽力向您显示相关和有用的信息。 For dates, that often means that whatever UTC value is stored within is displayed in your local timezone, which for you must be "GMT-0800 (Pacific Standard Time)." 对于日期,这通常意味着存储在其中的任何UTC值都显示在您的本地时区中,对于您来说,该时区必须为“ GMT-0800(太平洋标准时间)”。

If you want to display the time in UTC, you can write: 如果要以UTC显示时间,可以编写:

console.log(date.toUTCString())

This is what JSON.stringify is doing under the hood; 这就是JSON.stringifyJSON.stringify执行的操作; transporting dates with UTC helps simplify things when that information has to cross various timezones. 当信息必须跨越各个时区时,使用UTC传输日期可以简化事情。

However, that behavior doesn't seem to be what you're looking for. 但是,这种行为似乎并不是您想要的。 If you want the string to be local-timezone when you send it, you can write: 如果您希望在发送字符串时将其设置为本地时区,则可以编写:

console.log(date.toString())

如果您这样做,看来您可以得到想要的东西:

date.toDateString() + ' ' + date.toTimeString()

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

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