Thursday 22 September 2011

Dot.Net: How to write RSS date format in CSharp

Question:
In a RSS feed I need to write dates in the format RFC #822. How do I do this?
How to write a string in the RFC 1123 format??


Answer:
The Request for Comment 822 is the ARPA INTERNET TEXT MESSAGES specification.
The RFC 1123 (Requirements for Internet Hosts) is using the RFC 822.

The format looks like this:  "Sun, 15 Jun 2008 21:15:07 GMT"


In c# you can format your date this way using the 'r' (for RFC) format string:
   DateTime pubDate = DateTime.Now;
   string s = pubDate.ToString("r");


That is the same as if you would write:
   DateTime pubDate = DateTime.Now;
   string s = pubDate.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'");

Another useful format for dates is the sortable date format. (2009-06-15T13:45:30)
Use the 's' format string to get this.
   DateTime pubDate = DateTime.Now;
   string s = pubDate.ToString("s");

There are many other format strings you can use.


No comments: