FeliceM
FeliceM

Reputation: 4209

Issue parsing dateTime from one website

I am parsing datetime form a website to get day of the week, mont, year, time, using these 3 methods which are working fine with all the other sites I have tested but not with this one, which of course is the one I need to use.

protected string GetDayOfWeek(string dateTimeString)
{
    DateTime result = DateTime.Parse(dateTimeString);
    string dayOfWeek = Enum.GetName(typeof(DayOfWeek), result.DayOfWeek);

    return dayOfWeek;
}

protected string GetTimeOnly(string dateValue)
{
    return System.DateTime.Parse(dateValue).ToString("hh:mm");
}

protected string GetDateOnly(string dateValue)
{
    return System.DateTime.Parse(dateValue).ToString("ddd, MMM d, yyyy");
}

it keeps giving me this error:

System.FormatException not managed by the user code.
HResult=-2146233033 Message=String not recognised as valid DateTime

I have spent quite some time trying to sort out this problem without success. It was working fine until yesterday. If I visit the website or I check those feeds in a reader, the date time is there and even if I check the variable the time is there.

enter image description here

What am I missing? Any hint?

Update I have even tried to mashup several sites with yahoo pipes and it is working but as soon as I add the above mentioned site it gives me error. Obviously the problem is generated by something in the feeder website but I cannot find the reason.

Upvotes: 1

Views: 93

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98810

Becuase your string does not have a standart date/time format. That's why your DateTime.Parse will fail.

You can use DateTime.ParseExact method like;

string dateTimeString = "Sat, 01 Mar 2014 06:00:00 +0100";
var date = DateTime.ParseExact(dateTimeString,
                               "ddd',' dd MMM yyyy HH:mm:ss K",
                               CultureInfo.InvariantCulture);
Console.WriteLine(date);

Output will be;

3/1/2014 5:00:00 AM

Here a demonstration.

For more information, take a look at;

Upvotes: 2

Related Questions