user1810502
user1810502

Reputation: 529

Find time zone and time from given string of timestamp

I need to parse a timestamp and get both the time and the timezone from a string like the following,

Timestamp = "2013-09-17T14:55:00.355-08:00"

From the above string, I should be able to get time as 2:55pm and timezone as EST (Eastern)

Can anyone please let me know how the above parsing can be done.

Upvotes: 1

Views: 1293

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500575

You can get a DateTimeOffset which contains both the local time and the offset from UTC, using DateTimeOffset.ParseExact. However, there may be multiple time zones observing the same offset from UTC at that time, so you can't get the actual time zone.

Sample code:

using System;
using System.Globalization;

class Test
{
    static void Main()        
    {
        string text = "2013-09-17T14:55:00.355-08:00";
        DateTimeOffset dto = DateTimeOffset.ParseExact(text,
            "yyyy-MM-dd'T'HH:mm:ss.fffzzz",
            CultureInfo.InvariantCulture);
        Console.WriteLine(dto);
    }
} 

Or using my Noda Time library:

using System;
using NodaTime;
using NodaTime.Text;

class Test
{
    static void Main()        
    {
        string text = "2013-09-17T14:55:00.355-08:00";
        // Use GeneralIsoPattern just to get a default culture/template value
        OffsetDateTime odt = OffsetDateTimePattern.GeneralIsoPattern
            .WithPatternText("yyyy-MM-dd'T'HH:mm:ss.fffo<+HH:mm>")
            .Parse(text)
            .Value;
        Console.WriteLine(odt);
    }
} 

Upvotes: 5

Related Questions