java offsetdatetime_DateTimeOffset解析和自定义时区

我们正在将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);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值