DateTime WPF的奇怪行为 - 跨时区的WCF

Smi*_*thy 2 wpf wcf datetime datetimepicker

我有一个WPF客户端,它使用来自WCF服务的DateTime检索数据.

当我把我的电脑放在罗马时间(+1)时,我发现我的结果有些奇怪的行为.

我的WCF方法

        public IEnumerable<BookingType> BookingsForFollowingDayReport(DateTime date) {

        el = new ErrorLogging();
        el.CreateLog(db, new Entities.ErrorType() { DateLogged = DateTime.Now, Type = "DTE", Message = "Report Date: " + date.ToString() });

        var a = (from b in db.GetTable<BookingType>()
                 where b.TourStartDateTime >= date.Date && b.TourStartDateTime <= date.AddDays(1).Date
                 orderby b.TourStartDateTime
                 select b);

        if (a.Count() > 0) {
            el.CreateLog(db, new Entities.ErrorType() { DateLogged = DateTime.Now, Type = "DTE", Message = "Report Date: " + a.FirstOrDefault().TourStartDateTime });
        }

        return a;
    }
Run Code Online (Sandbox Code Playgroud)

该服务在某处的某个Web服务器上联机,现在我从我的WPF客户端调用它.请注意我的方法中的日志记录.

我的电话代码

    public static async Task<Bookings> GetBookingsReport(DateTime forWhen) {
        Bookings bookings = new Bookings();
        if (MyNetwork.IsOnline) {
            var bookingTypes = new ReportsServiceClient.BookingType[0];

                //forWhen = new DateTime(2013, 01, 10);
                bookingTypes = await ReportsServiceClient.BookingsForFollowingDayReportAsync(forWhen);


            bookings.TourBookings = (from b in bookingTypes
                                     where b.RecordType == "H"
                                     select new Booking(b)).ToList();

        }
        return bookings;
    }
Run Code Online (Sandbox Code Playgroud)

现在为了扼杀......

我使用DatePicker像这样的值调用来自XAML代码的'调用代码' :await DataManager.GetBookingsReport(datePicked.SelectedDate.Value);我将通过代码调试到BookingsForFollowingDayReportAsync调用点.

变量forWhen实际上是10/01/2013,太棒了!..接受我在WCF服务中的日志代码说09/01/2013发送通过.那么我取消注释我forWhen手动设置的行- 只是为了测试 - 并且它起作用,记录器说10/01/2013.

我已经在几天内对此进行了测试,如果我在DatePicker中选择了三天(过去或将来),例如记录了正确的日期,那么明天的日期总是有问题.

如果我将我的时区设置回英国格林威治标准时间,那么这个错误根本就不会发生.

我已经知道它可能与日期选择器有关,因为forWhen手动设置可以解决问题,但这怎么可能发生呢?

编辑1 我已经设法解决了这个问题,通过forWhen手动设置,使用forWhen像这样的值(因为看起来没有意义):

forWhen = new DateTime(forWhen.Year, forWhen.Month, forWhen.Day);
Run Code Online (Sandbox Code Playgroud)

我对这个问题以及我找到的解决方案感到困惑......有什么解释吗?

met*_*art 6

默认情况下,WCF DateTime根据本地时区序列化和反序列化对象.这意味着DateTime在您的情况下反序列化后,客户端在服务器上减少一个小时.显然你的时间部分是0(午夜),所以这可以解释昨天的日期.

其中一个解决方案是在将DateTime变量传递给服务之前显式设置DateTime.KindDateTimeKind.Unspecified:

DateTime forWhenSvcArg = DateTime.SpecifyKind(forWhen, DateTimeKind.Unspecified);
Run Code Online (Sandbox Code Playgroud)

当你通过调用构造函数设置为什么时,这就是你得到的.