public static TimeSpan?GetTime(object val, bool parse) { if (val is TimeSpan? && IOEx.IsNullable(val)) { return((TimeSpan?)val); } if (val is TimeSpan) { return((TimeSpan)val); } if (val is long) { return(new TimeSpan((long)val)); } long?n = NumberEx.GetLong(val); if (n != null) { return((n == 0) ? TimeSpan.Zero : new TimeSpan(n.Value)); } string s = parse ? val?.ToString() : null; if (s == null) { return((TimeSpan?)null); } TimeSpan ret; if (IsTimeSpan(s) && TryFromServer(s, out ret, TimeSpan.Zero)) { return(ret); } if (TimeSpan.TryParse(s, out ret)) { return(ret); } return(ParseTime(s)); }
public static DateTimeOffset?GetDate(object val, bool parse, bool isutc) { if (val is TimeSpan?) { return((isutc ? new DateTimeOffset(DateTime.Today.Ticks, TimeSpan.Zero) : new DateTimeOffset(DateTime.Today)) + ((TimeSpan?)val ?? TimeSpan.Zero)); } if (val is TimeSpan) { return(DateTimeOffset.MinValue + (TimeSpan)val); } if (val is DateTimeOffset? && IOEx.IsNullable(val)) { return((DateTimeOffset?)val); } if (val is DateTimeOffset) { return((DateTimeOffset)val); } if (val is DateTime? && IOEx.IsNullable(val)) { DateTime?dt = (DateTime?)val; if (dt == null) { return(null); } if (dt.Value <= DateTime.MinValue.AddHours(14)) { return(DateTimeOffset.MinValue); } if (dt.Value >= DateTime.MaxValue.AddHours(-14)) { return(DateTimeOffset.MaxValue); } return(isutc ? new DateTimeOffset(dt.Value.Ticks, TimeSpan.Zero) : new DateTimeOffset(dt.Value)); } if (val is DateTime) { DateTime dt = (DateTime)val; if (dt <= DateTime.MinValue.AddHours(14)) { return(DateTimeOffset.MinValue); } if (dt >= DateTime.MaxValue.AddHours(-14)) { return(DateTimeOffset.MaxValue); } return(isutc ? new DateTimeOffset(dt.Ticks, TimeSpan.Zero) : new DateTimeOffset(dt)); } string s = parse ? val?.ToString() : null; if (s == null) { return(null); } DateTimeOffset ret; if (IsRoundtripDate(s) && TryFromServerRoundtrip(s, out ret, DateTimeOffset.MinValue)) { return(ret); // is roundtrip date } if (IsIso8601Date(s) && ((isutc && TryFromServer(s, out ret, DateTimeOffset.MinValue)) || (!isutc && TryFromServerLocal(s, DateTimeOffset.Now.Offset.Hours, out ret, DateTimeOffset.MinValue)))) { return(ret); // is iso 8601 date } if (IsIso8601DateOnly(s) && TryFromServerDate(s, out ret, DateTimeOffset.MinValue)) { return(ret); // is iso 8601 date only } if (DateTimeOffset.TryParse(s, null, isutc ? DateTimeStyles.AssumeUniversal : DateTimeStyles.AssumeLocal, out ret)) { return(ret); // is formatted date } return(null); }