August 18, 2005

My Testing Of DateTime Parsing Capabilities

  
  public static void TestDateTime()
  {
    TestDateParsing(DateTime.Today.ToString());
    TestDateParsing("16/08/2005");
    TestDateParsing("01-08-2005");
    TestDateParsing("25 December 2005");
    TestDateParsing("");
    TestDateParsing("YES");
    /*
Test with: '18/08/2005 00:00:00'
  '18/08/2005'
  Difference in days from today: 0
Test with: '16/08/2005'
  '16/08/2005'
  Difference in days from today: 2
  Date is WITHIN the last '21' days
Test with: '01-08-2005'
  '01/08/2005'
  Difference in days from today: 17
  Date is WITHIN the last '21' days
Test with: '25 December 2005'
  '25/12/2005'
  Difference in days from today: -128
Test with: ''
  Exception caught: 'String was not recognized as a valid DateTime.'
setting dat e to Minimum Value '01/01/0001' Difference in days from today: 732175 Test with: 'YES' Exception caught: 'The string was not recognized as a valid
DateTime. There i s a unknown word starting at index 0.' setting date to Minimum
Value '01/01/0001' Difference in days from today: 732175 */ } public static void TestDateParsing(string str) { DateTime date; try { WL(string.Concat("Test with: \'", str, "\'")); date = DateTime.Parse(str); } catch (Exception ex) { WL(string.Concat(" Exception caught: \'",ex.Message, "\'
setting date to Minimum Value")); date = DateTime.MinValue; } WL(string.Concat(" \'", date.ToString("dd/MM/yyyy"), "\'")); TimeSpan time = DateTime.Now.Subtract(date); WL(string.Concat(" Difference in days from today: ",time.Days)); const int DAYLIMIT = 21; if ((time.Days <= DAYLIMIT) && (time.Days > 0)) { WL(string.Concat(" Date is WITHIN the last \'", DAYLIMIT,
"\' days")); } }
To parse the string "Mon, 08 Apr 2013 09:56:56 +0100" had to use the parse format "ddd, dd MMM yyyy HH':'mm':'ss K"
Like so:
string form = @"ddd, dd MMM yyyy HH':'mm':'ss K";
DateTime.TryParseExact(pubDateNode.Value, form, 
  System.Globalization.CultureInfo.CurrentCulture,
  System.Globalization.DateTimeStyles.AssumeLocal, 
  out when);

No comments: