我们正在将XML DateTime值解析为DateTimeOffset值 . 根据W3C XSD documentation for DateTime,类型可能有时区信息 .
我们的要求是:
如果以XML格式提供时区信息,请使用此时区
如果未提供时区信息,则假定它是预定义的可配置时区(不是服务器中的时区)中的本地时间 .
The Problem is that when a XML DateTime without a time zone is parsed into a DateTimeOffset, it uses the local (System) timezone by default. It seems not possible to override the default timezone and also not possible to identify wheter the timezone was parsed or added internally.
有没有什么方法可以指定DateTimeOffset解析使用的默认时区?
如果没有,如何识别在解析DateTimeOffset期间是否自动解析或添加时区?
对我来说,似乎不支持为.NET应用程序设置时区的方式与设置当前文化的方式相同 .
因此,解决此问题的唯一方法似乎是首先将值解析为DateTime并检查Kind属性 . 如果Kind未指定,则将值再次解析为DateTimeOffset:
/*
sample values:
- 2015-06-03T10:47:01
- 2015-06-03T07:47:01Z
- 2015-06-03T10:47:01+03:00
*/
DateTimeOffset dto;
var timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["DefaultTimeZone"]);
var dt = DateTime.Parse(value);
if (dt.Kind == DateTimeKind.Unspecified)
{
dto = new DateTimeOffset(dt, timeZone.GetUtcOffset(dt));
}
else
{
dto = DateTimeOffset.Parse(value);
}