Some while ago I developed a Settings system, where the SettingValue type should be checked. The DateTime.TryParse function did not do all the work I wanted it to do, so I thought ‘why not develop my own workaround’ ? It is posted below…
/// <summary> /// The IsDateTime function returns whether the given expression is a DateTime or not. /// </summary> /// <param name="expression">Expression to check for being DateTime.</param> /// <returns>Boolean</returns> /// <remarks> /// The DateTime expression can be given as ticks or as normal DateTime representation. /// </remarks> public static bool IsDateTime(object expression) { if(expression == null) return false;Bert Loedeman string stringExpression = System.Convert.ToString(expression); if(String.IsNullOrEmpty(stringExpression)) return false; // DateTime can be specified in ticks. In that case the string should be convertible // to a long (System.Int64) and fit in a specific range. long retLong; if(Int64.TryParse(stringExpression, out retLong)) { // Ticks: 0 = DateTime.MinValue, 0x2bca2875f4373fff = DateTime.MaxValue if((retLong < DateTime.MinValue.Ticks) || (retLong > DateTime.MaxValue.Ticks)) return false; return true; } DateTime retDateTime; return DateTime.TryParse(stringExpression, out retDateTime); }