tags:

views:

572

answers:

4

Is there a direct way to parse an iCalendar date to .net using c#? An iCalendar date looks like this:

2009-08-11T10:00+05:0000

I need to parse it to display it in a friendly format... thanks

A: 

You can use DateTime.Parse() to parse everything before the +. I do not know the iCalendar format specification but I assume after the + is the hours/minutes to add to the date before the +. So you could then use AddHours() and AddMinutes() to add the required bits to the DateTime returned by DateTime.Parse().

This requires a bit of string parsing but with a bit of regex you should be fine...

Simon Fox
+2  A: 

What about using an existing library that has full RFC 2245 compliance?

Cory Larson
+1  A: 
string strDate = "2009-08-11T10:00+05:0000";
DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
dtfi.FullDateTimePattern = "yyyy-MM-ddTHH:mmzzz";

DateTime dt = DateTime.Parse(c.Substring(0, c.Length-2), dtfi);

zzz is for time zone, but is only recognized when expressed like this: +xx:xx. I tested with your example, removing the last 2 0's then parsing with a custom DateTimeFormatInfo works.

najmeddine
A: 

Since this is not a standard format string, but you know the exact format, you can use DateTime.ParseExact and specify a custom format string, like this:

DateTime.ParseExact(d, "yyyy-MM-ddTHH:mmzzz00", CultureInfo.InvariantCulture);

The 'zzz' specifier represents the hours and minutes offset from UTC, and the two concluding zeros are just literals to match format with which you're dealing.

Jeff Sternal