enb081
enb081

Reputation: 4051

Convert java-like date string to DateTime in C#

I have dates in the following format:

Tue Mar 13 12:00:00 EST 2012

How can I convert them to DateTime in C#.net?

Upvotes: 3

Views: 1616

Answers (2)

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You can use TryParseExact:

class Program
{
    static void Main(string[] args)
    {
        var dtString = "Tue Mar 13 12:00:00 EST 2012".ConvertTimeZone();
        DateTime dt;
        var success = DateTime.TryParseExact(
            dtString,
            "ddd MMM dd HH:mm:ss zzz yyyy",
            CultureInfo.InvariantCulture,
            DateTimeStyles.None,
            out dt);

        Console.WriteLine(success);
        if (Debugger.IsAttached) { Console.ReadKey(); }
    }
}

public static class Extensions
{
    private static Dictionary<string, string> _timeZones =
        new Dictionary<string, string> { { "EST", "-05:00" } };

    public static string ConvertTimeZone(this string s)
    {
        var tz = s.Substring(20, 3);
        return s.Replace(tz, _timeZones[tz]);
    }
}

If the conversion is successful, success will be true and dt will have the date and time value.

Alright, so let's talk about this a little. Effectively I had to take the dive and commit to actually converting the time zone into the offset. This is very accurate, but it take some maintenance. The only thing you'll have to maintain is the Dictionary<string, string> _timeZones. You need to add all the time zones you want to support.

Upvotes: 3

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

There is DateTime.ParseExact. e.g. for "2009-05-08 14:40:52,531":

DateTime date = DateTime.ParseExact(
                   "2009-05-08 14:40:52,531", 
                   "yyyy-MM-dd HH:mm:ss,fff", 
                    System.Globalization.CultureInfo.InvariantCulture);

And for your case format should be something like: "ddd MMM dd HH:mm:ss zzz yyyy":

DateTime date = DateTime.ParseExact(
                   "Tue Mar 13 12:00:00 EST 2012", 
                   "ddd MMM dd HH:mm:ss zzz yyyy", 
                    System.Globalization.CultureInfo.InvariantCulture);

Problem is in getting timezone. Either K or zzz formatting option returns numeric time difference e.g +02:00 but you need letters instead. Possible solution will be to create helper method that will convert time offsets to letters representation. Unfortunately I don't see any other reasonable option to get this thing working.

var timeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern standard time");  
var formattedDate = "Tue Mar 13 12:00:00 EST 2012".Replace("EST",tzi.BaseUtcOffset.ToString());

Upvotes: 0

Related Questions