/// <summary> /// Parses the specified time string with these formats: /// 'HMMss', 'HHMMss', 'HMMssfff' and 'HHMMssfff'. /// </summary> /// <param name="timeString">The time string.</param> /// <param name="kind">The <see cref="DateTimeKind" /> kind. Default: Utc</param> /// <param name="style">The <see cref="DbTimeStyle"/> style. Default: Full</param> /// <returns></returns> /// <exception cref="ArgumentNullException">If <paramref name="timeString"/> is null</exception> /// <exception cref="ArgumentOutOfRangeException">If <paramref name="timeString"/> is empty</exception> /// <exception cref="FormatException">If <paramref name="timeString"/> cannot be parsed as a DbDate</exception> public static DbTime ParseTime(string timeString, DateTimeKind kind = DateTimeKind.Utc, DbTimeStyle style = DbTimeStyle.Full) { timeString.ExceptionIfNullOrTrimmedEmpty("timeString"); string dts = timeString.Trim(); if (!dts.All(Char.IsDigit)) { throw new FormatException(SR.DbDateTimeAcceptsDigitsOnlyFormatException); } // always fill with leading zeros to get around the missing digits parsing an int. // HMMSS is the parsed minimum dts = dts.PadLeft(6, '0'); if (style != DbTimeStyle.Full) // HHMMss { dts = dts.PadRight(9, '0'); } dts = dts.PadLeft(9, '0'); // fill in missing leading zeros if (dts.Length == 9) { // Time: HHMMSSmmm int hour = Int32.Parse(dts.Substring(0, 2)); int minute = Int32.Parse(dts.Substring(2, 2)); int second = Int32.Parse(dts.Substring(4, 2)); int millisecond = Int32.Parse(dts.Substring(6, 3)); try { return(new DbTime(hour, minute, second, millisecond, kind)); } catch (Exception ex) { throw new FormatException(ex.Message, ex); } } throw new FormatException(SR.DbTimeInvalidFormatException); }
public static DbTime?SafeParseNullableTime(object value, object fieldInfo = null, DateTimeKind kind = DateTimeKind.Utc, DbTimeStyle style = DbTimeStyle.Full) { if (value != null && !(value is DBNull)) { try { string timeString; switch (Type.GetTypeCode(value.GetType())) { case TypeCode.Empty: return(null); case TypeCode.String: timeString = (string)value; break; case TypeCode.Int32: return(new DbTime(Convert.ToInt32(value), kind)); case TypeCode.Int64: return(new DbTime(Convert.ToInt32(value), kind)); case TypeCode.UInt32: return(new DbTime(Convert.ToInt32(value), kind)); case TypeCode.UInt64: return(new DbTime(Convert.ToInt32(value), kind)); case TypeCode.DateTime: var dt = (DateTime)value; return((DbTime)dt); default: timeString = value.ToString(); break; } timeString = timeString.Trim(); if (String.IsNullOrEmpty(timeString)) { return(null); } if (timeString == "0") { return(DbTime.MinValue); } return(DbDateTime.ParseTime(timeString, kind, style)); } catch (Exception ex) { throw FormattedException(ex, value, value.GetType(), typeof(DbDate), fieldInfo); } } return(null); }