Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c# - Parsing ISO 8601 with timezone to .NET datetime

I have an ISO 8601 timestamp in the format:

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

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

Examples:

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

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

How can I parse it to a .NET Framework DateTime with correct TimeZone supplied?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

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.)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...