Pergunta

How Can I convert following date string to dateTime:

Fri, 18 Dec 2009 9:38 am PST

I tried DateTime.Parse(string)

I got following error:

The string was not recognized as a valid DateTime. There is an unknown word starting at index 25. System.SystemException {System.FormatException}

UPDATE

I tried to get weather from yahoo and I tried to get date like this:

Date = DateTime.Parse(feed.Element(yWeatherNS + "condition").Attribute("date").Value),

I debugged it. date attribute is correct (like above).

Thanks.

Foi útil?

Solução

I don't think there's anything in the BCL which will parse time zone abbreviations. (They should be avoided where possible anyway, as they can be ambiguous.)

If you don't mind losing the time zone information, you can use something like this:

using System;
using System.Globalization;

static class Test
{
    static void Main()
    {
        string text = "Fri, 18 Dec 2009 9:38 am PST";
        DateTime parsed = TrimZoneAndParse(text);
        Console.WriteLine(parsed);
    }

    static DateTime TrimZoneAndParse(string text)
    {
        int lastSpace = text.LastIndexOf(' ');
        if (lastSpace != -1)
        {
            text = text.Substring(0, lastSpace);
        }
        return DateTime.ParseExact(text,
            "ddd, dd MMM yyyy h:mm tt",
            CultureInfo.InvariantCulture);
    }
}

Note that that assumes a fixed date/time format and culture. Your needs may vary, and you should also consider using TryParse or TryParseExact if this is user input.

Outras dicas

If DateTime.Parse can't figure it out automatically, you can use DateTime.ParseExact where you specify the format being used.

In your case this would be something like, you'll need to replace the 'PST' yourself however:

CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = "Fri, 18 Dec 2009 9:38 am PST";
dateString = dateString.Replace("PST", "-08:00");
string format = "ddd, dd MMM yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);

If your program needs to work with different timezone abbrevations, you'll have to build a Dictionary with abbrevation to time zone offset conversions.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top