C# UTC DateTime query in WCF/.NET

心已入冬 提交于 2019-12-31 01:44:06

问题


This is a very simple, (hopefully) question. I am new to working with DateTime conversion in .NET.

I have a WCF service which has a DateTime property - call it BookingDate.

Someone passes that to my WCF service in the format:

<a:BookingDate>2012-03-26T17:03:00-04:00</a:BookingDate>

The server that it is sitting on is set to a timezone of UTC (Lisbon, London, Dublin).

When I store the corresponding value in the database, it sets the value to be:

2012-03-26 22:03

I assumed, I think incorrectly that the .NET framework (as part of the WCF serialize/deserialize process) would pop this into a .Net Datetime of UTC for me (as there is the minus offset of 4 hours as above)

I was expecting: 2012-03-26 21:03

My question is thus: would I need to call:

var date = fromClientWCFService.BookingDate.ToUniversalTime();

in order to get the 21:03 time that I am expecting?

If not, is there a WCF setting to tell my service to convert DateTimes to UTC, rather than the server timezone?

Thanks in advance

Mark

EDIT:

From 1 answer, I can see that DateTimeOffset can be used. Following on from this, would the following work: var offset = DateTimeOffset.Parse("2012-03-26T17:03:00-0400"); to return the result: 2012-03-26 21:03


回答1:


Instead of using the DateTime structure, you should use the DateTimeOffset structure.

The DateTimeOffset structure captures the offset from a specified time (it's not UTC by default, it's defined by the scope of your application, but the most common offset would be from UTC) along with the date/time information, and that information will flow through WCF calls (as well as to a database, assuming it supports the type. SQL Server in this case has the datetimeoffset data type from 2008 on).

As a matter of fact, using DateTimeOffset is the preferred methods of dealing with date/time data in almost all situations. Note from the previous link:

These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, DateTimeOffset should be considered the default date and time type for application development.




回答2:


If your server's timezone is on Lisbon/London/Dublin time, it is not UTC. You will either want to change the time zone of your server, or express the date/time value in UTC form when you update it in your database.



来源:https://stackoverflow.com/questions/9878560/c-sharp-utc-datetime-query-in-wcf-net

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