C#UTC日期时间查询WCF / .NET日期、时间、UTC、WCF

2023-09-05 01:02:03 作者:夨薏後ㄆ從來

这是一个非常简单的,(希望)的问题。我是新来与日期时间转换.NET的。

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

我有一个WCF服务有一个DateTime属性 - 称之为BookingDate

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

有人经过,要在格式我的WCF服务:

Someone passes that to my WCF service in the format:

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

这是坐在上的服务器设置为UTC(里斯本,伦敦,都柏林)的时区。

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

我认为,我认为不正确的.NET框架(作为WCF序列化/反序列化过程的一部分)会弹出这个到UTC的净日期时间对我来说(因为是零下4个小时的上述偏移)

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)

我所期待的: 2012-03-26 21:03

我的问题是这样:我需要调用:

My question is thus: would I need to call:

var date = fromClientWCFService.BookingDate.ToUniversalTime();

为了获得21:03的时间,我期待?

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

如果不是,是否有一个WCF设置来告诉我的服务,以创建DateTime对象转换为UTC,而不是服务器时区?

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

在此先感谢

标记

编辑:

1个答案,我可以看到的DateTimeOffset都可以使用。根据这一点,将以下工作:无功补偿= DateTimeOffset.Parse(2012-03-26T17:03:00-0400); 返回结果: 2012-03-26 21:03

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

推荐答案

而不是使用的 的DateTime 结构,你应该使用的 的DateTimeOffset 结构。

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

的DateTimeOffset 结构捕获从指定的时间偏移量(这不是默认UTC,它是由范围定义的您的应用,但最常见的偏移将是从UTC)的沿的与日期/时间信息,并且该信息将流过的WCF调用(以及到一个数据库,假设它支持的类型。SQL Server的在此本案具有 DATETIMEOFFSET 数据类型从2008年的)。

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).

由于事实上,使用的DateTimeOffset 是$ P $与日期/时间数据处理的pferred方法差不多的所有的情况的。注意从previous链接:

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:

在这些用途的DateTimeOffset值比那些更为常见   DATETIME值。其结果是,的DateTimeOffset应考虑   默认的日期和时间类型的应用程序开发。

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.