开发者

How do you format and pass the date for better interoperable compatibility?

开发者 https://www.devze.com 2023-02-16 14:35 出处:网络
In our production environment of 12 servers we have an issue with the code var date = DateTime.Parse(\"Thu, 10 Mar 2011 13:15:33 GMT\");

In our production environment of 12 servers we have an issue with the code

var date = DateTime.Parse("Thu, 10 Mar 2011 13:15:33 GMT");

and this is not all the time and just on few of the servers (once per month maybe) it will throw the

System.FormatException: String was not recognized as a valid DateTime.
at System.DateTimeParse.Parse(String, DateTimeFormatInfo, DateTimeStyles)

The date "Thu, 10 Mar 2011 13:15:33 GMT" is开发者_StackOverflow中文版 a real example for today it originates from another environment and is created in the following way

string.Format("{0:R}", ExpiresOn.ToUniversalTime())

The second day we plug servers back in the farm and they will continue to work fine.

  • There is any way to avoid this ?
  • Because this information is opaque for the consumers we think switching to ticks is this better ?
  • Any good practices ?

Thanks


Always use the CultureInfo.InvariantCulture. This is a rule. Use it for parsing of Dates, of numbers (especially floats/doubles/decimals), for ToString(ing) Dates, numbers (especially floats/doubles/decimals) etc. And if you handle date, always think if it would be better to handle them in UTC or in your local timezone. If you have to handle coordination between servers/persons in multiple timezones, always use (store) UTC dates.


This is with what I came up according to previous answer

var original = DateTime.Now;
var stringified = original.ToString("r",CultureInfo.InvariantCulture);

and on the consumer side/server

var restored = DateTime.ParseExact(stringified, "r", CultureInfo.InvariantCulture);

We did some testing and so far it looks good. If you feel like I'm wrong or it can be done simpler let me know thanks.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号