views:

154

answers:

0

In Windows, i want to parse a string as a date using an exact format string.

For example, given the string

"6/12/2010"

and the format:

"M/d/yyyy"

i want to convert the string to a date, while ensuring that the date matches the format.

i also need to be able to specify the Y2K sliding window, pivot. This means that if a 2-digit year is (correctly) entered, i will specify that number of years in the future i would consider the year to be. e.g.:

Two-digit Year    Pivot    Four-digit year
==============    =====    ===============
30                +0       1929
30                +18      1929
30                +19      1929
30                +20      2029
30                +21      2029
30                +100     2029

.NET already provides a DateTime.ParseExact function, which performs nearly exactly what i need:

date = DateTime.ParseExact("6/12/2010", 
         DateTimeFormatInfo.ShortDatePattern,
         Thread.CurrentThread.CurrentCulture);

Except i can't tell it the 100-year pivot value.

More examples:

String        Format Specifier        Date
"6/7/2029"   "M/d/yyyy"             6/7/2029
"6/7/29"     "M/d/yyyy"             (invalid, year too short)
"6/7/29"     "M/d/yy"               6/7/1929  (+0 pivot)
"6/7/29"     "M/d/yy"               6/7/2029  (+100 pivot
"6/7/29"     "M/d/yy"               6/7/2029  (+50 pivot)
"6/7/29"     "M/d/yy"               6/7/2029
"6/7/2029"   "M.d.yyyy"             (invalid, incorrect separators)
"6.7.2029"   "M.d.yyyy"             6/7/2029
"6.7.2029"   "M-d-yyyy"             (invalid, incorrect separators)
"6/7/2029"   "M/dd/yyyy"            (invalid, days requires leading zero)
"6/07/2029"  "M/dd/yyyy"            (invalid, days requires leading zero)    
"6/07/2029"  "MM/dd/yyyy"           (invalid, months requires leading zero)
"06/07/2029  "MM/dd/yyyy"           6/7/2029
"06/07/2029" "MM/d/yyyy"            (invalid, days should not have leading zero)
"06/7/2029"  "MM/d/yyyy"            6/7/2029

i know that Windows doesn't have native API to convert a string to a date.

Is there any established code out there that will convert a string to a date using a format specifier? Computers have been around for a while now; someone must have solved this problem already.

Here is a list of some sample format specifiers that you could be expected to see in Windows:

  • M/d/yyyy
  • M/d/yy
  • M/dd/yyyy
  • M/dd/yy
  • MM/d/yyyy
  • MM/d/yy
  • MM/dd/yyyy
  • MM/dd/yy
  • d/M/yyyy
  • d/M/yyy
  • d/MM/yyyy
  • d/MM/yy
  • dd/M/yyyy
  • dd/M/yy
  • dd/MM/yyyy
  • dd/MM/yy
  • yyyy/M/d
  • yy/M/d
  • yyyy/MM/d
  • yy/MM/d
  • yyyy/MM/dd
  • yy/MM/dd
  • dd MM yyyy
  • dd.MM.yyyy

See also