Should I use DateTime.Now or DateTime.UtcNow in HttpCookie.Expires and HttpCachePolicy.SetExpires?

偶尔善良 提交于 2019-12-21 03:19:12

问题


Should I use DateTime.Now or DateTime.UtcNow in HttpCookie.Expires and HttpCachePolicy.SetExpires?

Cookies are sending 'GMT' time, but I don't know what happen if I send DateTime.Now.AddDays(3) if I would be in GMT+5. Same with Expires HTTP header (sec 14.21).

What should I use?


回答1:


It doesn't matter in this case.

Internally, the first thing .SetExpires does is convert your supplied datetime into UTC, before setting it on the cookie.

Bear in mind, as long as your datetime consumer uses the DateTime class correctly, then the two are the same - it is just that one is "baselined" to UTC and the other isn't:

20110701T14:00:00-1:00 (British Summer Time)

and

20110701T13:00:00+0:00 (UTC)

represent exactly the same datetime, namely 1pm UTC.

As long as the consumer handles this correctly (which it seems to, having looked in reflector) then it makes no difference.

If you were taking this and passing it in as a time string, then of course, it may well make a difference, but not in this case.

You can see the effect with the following code (assuming you are not in UTC yourself - if you are - change your settings to test!). They both output the same datetime, once you've asked for it to be converted to UTC.

WriteDateTime(DateTime.Now);
WriteDateTime(DateTime.UtcNow);

public static void WriteDateTime(DateTime dateTime)
{
   Console.WriteLine(dateTime.ToUniversalTime().ToLongTimeString());   
}



回答2:


You should be using DateTime.UtcNow method because thats the time standard used for cookies. UTC is equivilant to GMT.

From MSDN: System.DateTime.UtcNow

Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).

Refer to this for an explanation between them.



来源:https://stackoverflow.com/questions/4849744/should-i-use-datetime-now-or-datetime-utcnow-in-httpcookie-expires-and-httpcache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!