简体   繁体   中英

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 :)

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#

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.

eg

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM