fork download
  1. using System;
  2. using System.Text;
  3. using System.Text.RegularExpressions;
  4.  
  5. struct MyDate
  6. {
  7. public int? Year, Month, Day, Hour, Minute;
  8.  
  9. private static readonly Regex dtRegex = new Regex(
  10. @"^(?<year>\d{4})?-(?<month>\d\d)?-(?<day>\d\d)?"
  11. + @"(?:T(?<hour>\d\d)?:(?<minute>\d\d)?)?$",
  12. RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
  13.  
  14. public static bool TryParse(string input, out MyDate result)
  15. {
  16. Match match = dtRegex.Match(input);
  17. result = default(MyDate);
  18.  
  19. if (match.Success)
  20. {
  21. if (match.Groups["year"].Success)
  22. result.Year = Int32.Parse(match.Groups["year"].Value);
  23. if (match.Groups["month"].Success)
  24. result.Month = Int32.Parse(match.Groups["month"].Value);
  25. if (match.Groups["day"].Success)
  26. result.Day = Int32.Parse(match.Groups["day"].Value);
  27. if (match.Groups["hour"].Success)
  28. result.Hour = Int32.Parse(match.Groups["hour"].Value);
  29. if (match.Groups["minute"].Success)
  30. result.Minute = Int32.Parse(match.Groups["minute"].Value);
  31. }
  32.  
  33. return match.Success;
  34. }
  35.  
  36. public static MyDate Parse(string input)
  37. {
  38. MyDate result;
  39. if (!TryParse(input, out result))
  40. throw new ArgumentException(string.Format("Unable to parse MyDate: '{0}'", input));
  41.  
  42. return result;
  43. }
  44.  
  45. public override string ToString()
  46. {
  47. return string.Format("{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}", Year, Month, Day, Hour, Minute);
  48. }
  49.  
  50. public static implicit operator MyDate(string input)
  51. {
  52. return Parse(input);
  53. }
  54. }
  55.  
  56. class Program
  57. {
  58. static void Main(string[] args)
  59. {
  60. foreach (var testcase in new [] {
  61. "2011-11-07T11:17",
  62. "-11-07T11:17",
  63. "2011--07T11:17",
  64. "2011-11-T11:17",
  65. "2011-11-07T:17",
  66. "2011-11-07T11:",
  67. // extra:
  68. "--T11:17", // (11:17 am, no date, only time)
  69. "-11-07", // (november the 7th, no year, no time)
  70. // failures:
  71. "2011/11/07 T 11:17",
  72. "no match" })
  73. {
  74. MyDate parsed;
  75. if (MyDate.TryParse(testcase, out parsed))
  76. Console.WriteLine("'{0}' -> Parsed into '{1}'", testcase, parsed);
  77. else
  78. Console.WriteLine("'{0}' -> Parse failure", testcase);
  79. }
  80. }
  81. }
  82.  
  83.  
Success #stdin #stdout 0.05s 38104KB
stdin
Standard input is empty
stdout
'2011-11-07T11:17' -> Parsed into '2011-11-07T11:17'
'-11-07T11:17' -> Parsed into '-11-07T11:17'
'2011--07T11:17' -> Parsed into '2011--07T11:17'
'2011-11-T11:17' -> Parsed into '2011-11-T11:17'
'2011-11-07T:17' -> Parsed into '2011-11-07T:17'
'2011-11-07T11:' -> Parsed into '2011-11-07T11:'
'--T11:17' -> Parsed into '--T11:17'
'-11-07' -> Parsed into '-11-07T:'
'2011/11/07 T 11:17' -> Parse failure
'no match' -> Parse failure