解析ISO 8601与时区为.NET日期时间 [英] Parsing ISO 8601 with timezone to .NET datetime

查看:506
本文介绍了解析ISO 8601与时区为.NET日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在格式 ISO 8601 时间戳:

YYYY-MM-DDThh:mm:ss[.nnnnnnn][{+|-}hh:mm]

YYYY-MM-DDThh:mm:ss[{+|-}hh:mm]

例如:

2013-07-03T02:16:03.000+01:00

2013-07-03T02:16:03+01:00

我如何可以解析到一个.NET框架的DateTime 正确的时区提供的?

DateTime.TryParse 不起作用,因为对于尾随信息的时区

The DateTime.TryParse doesn't work because the trailing info regarding the TimeZone.

推荐答案

您应该可以使用到格式化的DateTimeOffset K 自定义格式说明。然后,您可以将其转换为的DateTime 之后,如果你想。样品code:

You should be able to format it using DateTimeOffset and the K custom format specifier. You can then convert that to a DateTime afterwards if you want to. Sample code:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        string text = "2013-07-03T02:16:03.000+01:00";
        string pattern = "yyyy-MM-dd'T'HH:mm:ss.FFFK";
        DateTimeOffset dto = DateTimeOffset.ParseExact
            (text, pattern, CultureInfo.InvariantCulture);
        Console.WriteLine(dto);
    }
}

有一点需要注意的是,这是严重命名 - 它实际上不是一个时间段,它只是UTC偏移。它的的真正告诉你原来的时区。 (可以有几个不同的时区观察同一同时偏移。)

One thing to note is that this is badly named - it's not actually a time zone, it's just a UTC offset. It doesn't actually tell you the original time zone. (There can be several different time zones observing the same offset at the same time.)

或者与野田时间(不稳定的版本,这将成为1.2 pretty的很快):

Or with Noda Time (unstable version, which will become 1.2 pretty soon):

string text = "2013-07-03T02:16:03.000+01:00";
OffsetDateTimePattern pattern = OffsetDateTimePattern.ExtendedIsoPattern;
OffsetDateTime odt = pattern.Parse(text).Value; 
Console.WriteLine(odt);

这篇关于解析ISO 8601与时区为.NET日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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