将.NET时间从UTC转换为指定的TimeZone时,.NET PCL异常 [英] .NET PCL exception while converting time from UTC to specified TimeZone

查看:117
本文介绍了将.NET时间从UTC转换为指定的TimeZone时,.NET PCL异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Xamarin Studio中使用C#开发一个项目。它的一个.net PCL项目和我的个人资料是78.我的问题是,我无法将一个DateTime从UTC转换为指定的时区。我使用下面的代码将DateTime从UTC转换为指定的本地TimeZone。

  DateTime dateTime =(TimeZoneInfo.ConvertTime(DateTime.SpecifyKind (DateTime.UtcNow,DateTimeKind.Utc),profile.TimeZone)); 

我正在下降例外


dateTime参数的Kind属性是DateTimeKind.Utc,但
sourceTimeZone参数不等于TimeZoneInfo.Utc。


在PCL 中,TimeZoneInfo.ConvertTime 没有指定 TimeZoneInfo sourceTimeZone 的参数。它只有2个重载,具有以下参数。


ConvertTime(DateTime,TimeZoneInfo)& ConvertTime(DateTimeOffset,
TimeZoneInfo)


TimeZoneInfo仅用于指定目的地TimeZoneInfo。



另外它没有 TimeZoneInfo.ConvertTimeFromUtc,TimeZoneInfo.ConvertTimeToUtc 方法。



请有人帮我解决这个问题。

解决方案

添加汉斯的评论:


这完全是设计的。时区转换需要具有跟踪世界各地时区规则的数据库的操作系统。在台式机上可用,不受限于像手机这样的设备。没有数据库,您只能知道有关UTC和设备配置的时区。您不能使用PCL,如果这是一个要求,使用商业网络服务为您的转换将成为解决方法。


有看看 Noda时间。这是.NET的日期/时间库,它具有自己的时区数据,因此不必依赖于操作系统。它也支持PCL。


I am developing a project in Xamarin Studio using C#. Its a .net PCL project and my profile is 78. My problem is, i am unable to convert a DateTime from UTC to specified timezone. I am using below code to convert DateTime from UTC to specified local TimeZone.

   DateTime dateTime = (TimeZoneInfo.ConvertTime (DateTime.SpecifyKind (DateTime.UtcNow, DateTimeKind.Utc), profile.TimeZone));

I am getting below exception

The Kind property of the dateTime parameter is DateTimeKind.Utc, but the sourceTimeZone parameter does not equal TimeZoneInfo.Utc.

In PCL TimeZoneInfo.ConvertTime doesn't have a parameter for specifying the TimeZoneInfo sourceTimeZone. It has only 2 overloads with below parameters.

ConvertTime(DateTime, TimeZoneInfo) & ConvertTime(DateTimeOffset, TimeZoneInfo)

TimeZoneInfo exist only to specify destination TimeZoneInfo.

Also it doesn't have TimeZoneInfo.ConvertTimeFromUtc, TimeZoneInfo.ConvertTimeToUtc Methods.

Please someone help me to fix this.

解决方案

To add to Hans's comment:

This is all entirely by design. Timezone conversions requires an operating system with a database that keeps track of the timezone rules across the world. Available on a desktop class machine, not available on limited devices like a phone. Without the database, you can only know something about UTC and the timezone for which the device was configured. You cannot use PCL if this is a requirement, using a commercial web service to make the conversion for you would be a workaround.

Have a look at Noda Time. This is a Date/Time library for .NET which has its own time zone data so it doesn't have to rely on the OS. It also supports PCLs.

这篇关于将.NET时间从UTC转换为指定的TimeZone时,.NET PCL异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆