bflemi3
bflemi3

Reputation: 6790

Parse date string from xml feed to DateTime

I have a few different xml feeds that I am consolidating into one "feed" for a website I'm working on (c#). Most of the feeds follow the rss2.0 standard, namely the news feeds and the facebook feed. However, I'm also pulling twitter and they seem to use their own standard from what I can tell. I am having an issue pulling the publish date from facebook and twitter because they are in slightly different formats.

facebook = <lastBuildDate>Thu, 12 Jan 2012 00:06:54 +0000</lastBuildDate>

twitter = <created_at>Wed Jan 11 23:48:15 +0000 2012</created_at>

I'm not quite sure where to start here, thanks for the help :)

Upvotes: 3

Views: 5136

Answers (2)

Shurugwi
Shurugwi

Reputation: 168

You will need to do a DateTime.ParseExact if the format is not recognized.

Using the following class:

public static class Extensions
{
    public static DateTime ParseTwitterDateTime(this string date)
    {
        const string format = "ddd MMM dd HH:mm:ss zzzz yyyy";
        return  DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
    }

    public static DateTime ParseFacebookDateTime(this string date)
    {
        const string format = "ddd, dd MMM yyyy HH:mm:ss zzzz";
        return  DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);
    }
}

You should be able to parse the values using the extension method on the string.

Used as reference: Twitter date parsing in C#

Upvotes: 13

CD Jorgensen
CD Jorgensen

Reputation: 1391

If you know that it's from, say, facebook, and facebook consistently uses the same date format, you can just parse the string for its components (day of week, month, time, etc.), re-arrange them into an order that C# recognizes, and then use DateTime.Parse() to convert them to a date. You will have to have a different re-arrange method for each feed.

e.g.

Thu, 12 Jan 2012 00:06:54 +0000

becomes

Jan 12, 2012 00:06:54 +0000

or something like that (not sure if C# will actually parse that, so modify as needed).

Upvotes: 0

Related Questions