source: xmlrpcnet/trunk/fuentes/src/DateTime8601.cs @ 379

Last change on this file since 379 was 379, checked in by hectorgh, 5 years ago

adding project files

File size: 1.5 KB
Line 
1using System;
2using System.Globalization;
3using System.Text.RegularExpressions;
4
5namespace CookComputing.XmlRpc
6{
7  public static class DateTime8601
8  {
9    static Regex _dateTime8601Regex = new Regex(
10        @"(((?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}))|((?<year>\d{4})(?<month>\d{2})(?<day>\d{2})))"
11      + @"T"
12      + @"(((?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}))|((?<hour>\d{2})(?<minute>\d{2})(?<second>\d{2})))"
13      + @"(?<tz>$|Z|([+-]\d{2}:?(\d{2})?))");
14
15
16    static public bool TryParseDateTime8601(string date, out DateTime result)
17    {
18      result = DateTime.MinValue;
19      var m = _dateTime8601Regex.Match(date);
20      if (m == null)
21        return false;
22      string normalized = m.Groups["year"].Value + m.Groups["month"].Value + m.Groups["day"].Value
23        + "T"
24        + m.Groups["hour"].Value + m.Groups["minute"].Value + m.Groups["second"].Value
25        + m.Groups["tz"].Value;
26      var formats = new string[]
27      {
28        "yyyyMMdd'T'HHmmss", 
29        "yyyyMMdd'T'HHmmss'Z'", 
30        "yyyyMMdd'T'HHmmsszzz", 
31        "yyyyMMdd'T'HHmmsszz", 
32      };
33      // Compact Framework doesn't support TryParseExact()
34      try
35      {
36        result = DateTime.ParseExact(normalized, formats, CultureInfo.InvariantCulture,
37                System.Globalization.DateTimeStyles.AdjustToUniversal);
38        return true;
39      }
40      catch (Exception)
41      {
42        return false;
43      }
44    }
45  }
46}
Note: See TracBrowser for help on using the repository browser.