private static void CheckDateRoundtrips(DateTime now) { var ms = (now - new DateTime(1970, 1, 1)).Ticks / 10000; var serializedNow = AspTools.SerializeDateTimeToString(now); Assert.AreEqual(string.Format("/Date({0})/", ms), serializedNow); var jsonString = new JsonString(serializedNow); Debug.WriteLine(jsonString.ToString()); var dNow = AspTools.ParseStringToDateTime(jsonString); Assert.AreEqual( new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond), new DateTime(dNow.Year, dNow.Month, dNow.Day, dNow.Hour, dNow.Minute, dNow.Second, dNow.Millisecond)); }
/// <summary> /// parses a string in the format '\/Date(700000+0500)\/' to a datetime value. /// </summary> /// <param name="str">must be a non-null, valid serialized datetime string</param> /// <returns>Valid datetime</returns> /// <exception cref="AspDateTimeException">throws a AspDateTimeException if the str is not in the correct format</exception> /// <exception cref="ArgumentException">thrown if str is null</exception> /// <see cref="http://msdn.microsoft.com/en-us/library/bb412170.aspx"/> public static DateTime ParseStringToDateTime(JsonString str) { Contract.Requires(str != null); var match = PARSE_DATETIME_STR.Match(str); if (!match.Success) throw new AspDateTimeException(string.Format("'{0}' is not a valid format ({1})", str.Value, DATETIME_REGEX_STR)); var matchedValue = match.Groups[1].Value; bool isUtc = true; var indexOf = matchedValue.IndexOf('+'); if (indexOf > -1) { isUtc = false; matchedValue = matchedValue.Substring(0, indexOf); } try { var ms = long.Parse(matchedValue); if (ms > 0) { return new DateTime(1970, 1, 1, 0, 0, 0, isUtc ? DateTimeKind.Utc : DateTimeKind.Local) + new TimeSpan(ms * 10000); } else { return new DateTime(1970, 1, 1, 0, 0, 0, isUtc ? DateTimeKind.Utc : DateTimeKind.Local) - new TimeSpan(-ms * 10000); } } catch (FormatException fe) { throw new AspDateTimeException("datetime string is not in the correct format; cannot parse to long", fe); } }