@manhng

Welcome to my blog!

SqlDataReader with DateTime

July 21, 2018 14:36

SqlDataReader Extensions (edit)

    public class SqlDataReaderExt
    {
        public static T CheckNull(object obj)
        {
            return (obj == DBNull.Value ? default(T) : (T)obj);
        }

        public static DateTime CheckNullDate(object obj, string dateFormat)
        {
            if (obj == DBNull.Value) return DateTimeExt.SQL_DEFAULT;
            return DataHelper.GetDate(obj.ToString(), dateFormat);
        }
    }

DataHelper & CommonStrings

    public class DataHelper
    {
        public static DateTime GetDate(string dateString, string dateFormat)
        {
            try
            {
                DateTime.TryParseExact(dateString,
                                   dateFormat, //Example MM/dd/yyyy, dd/MM/yyyy
                                   CultureInfo.InvariantCulture,
                                   DateTimeStyles.None,
                                   out DateTime dt);
                return DateTime.MinValue == dt ? DateTimeExt.SQL_DEFAULT : dt;
            }
            catch (Exception ex)
            {
                MyLogger.Log.Error(ex.ToString());
                return DateTimeExt.SQL_DEFAULT;
            }
        }
    }
    public static class CommonStrings
    {
        public static string DateFormatMMDDYYYY = "MM/dd/yyyy";
        public static string DateFormatDDMMYYYY = "dd/MM/yyyy";
    }

SqlDataReader with DateTime

    public static class DateTimeExt
    {
        public static DateTime SQL_DEFAULT = new DateTime(1900, 1, 1);

        public static bool IsDefaultValue(this DateTime dateTime)
        {
            return dateTime == SQL_DEFAULT;
        }

        public static DateTime GetDate(string dateString, string dateFormat)
        {
            try
            {
                DateTime.TryParseExact(dateString,
                                   dateFormat, //Example MM/dd/yyyy, dd/MM/yyyy
                                   CultureInfo.InvariantCulture,
                                   DateTimeStyles.None,
                                   out DateTime dt);
                return DateTime.MinValue == dt ? DateTimeExt.SQL_DEFAULT : dt;
            }
            catch (Exception ex)
            {
                MyLogger.Log.Error(ex.ToString());
                return DateTimeExt.SQL_DEFAULT;
            }
        }
    }

Categories

Recent posts