C#常用数据转换等工具类(自用笔记)

        public static DateTime? ToDateTime(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(obj);
                }
                catch
                {
                    return null;
                }
            }
        }
        /// 
        /// 日期格式化
        /// 
        /// 日期(可为Null)
        /// 日期格式化的格式(默认值'年月日',缺省值'年月日时分秒')
        /// 日期为Null时是否用Now代替?
        /// 
        public static string ToDateString(DateTime? dt, string format = "yyyy-MM-dd", bool defNow = true)
        {
            try
            {
                if (dt.HasValue)
                {
                    if (!string.IsNullOrWhiteSpace(format))//有格式
                    {
                        return dt.Value.ToString(format);//按格式转换
                    }
                    else//无格式,按完整的'年月日时分秒'转换
                    {
                        return dt.Value.ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                else//dt==Null
                {
                    if (defNow == true)//用Now代替
                    {
                        if (!string.IsNullOrWhiteSpace(format))
                        {
                            return DateTime.Now.ToString(format);
                        }
                        else
                        {
                            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                    else
                    {
                        return "";
                    }
                }
            }
            catch
            {
                return "";
            }
        }

        /// 
        /// 取得某月的第一天
        /// 
        /// 要取得月份第一天的时间
        /// 
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// 
        /// 取得某月的最后一天
        /// 
        /// 要取得月份最后一天的时间
        /// 
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }
        /// 
        /// 取得上个月第一天
        /// 
        /// 要取得上个月第一天的当前时间
        /// 
        private DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }
        /// 
        /// 取得上个月的最后一天
        /// 
        /// 要取得上个月最后一天的当前时间
        /// 
        private DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }
        /// 
        /// 取得下个月的第一天
        /// 
        /// 
        /// 
        private DateTime FirstDayOfNextMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1);
        }
        /// 
        /// 取得下个月的最后一天
        /// 
        /// 
        /// 
        private DateTime LastDayOfNextMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(2).AddDays(-1);
        }

        //decimal
        public static decimal ToDecimal(object obj)
        {
            return ToDecimal(obj, 2, true, 0);//默认2位小数,四舍五入,默认值0
        }
        /// 
        /// object转decimal
        /// 
        /// obj
        /// 小数位数
        /// 是否四舍五入
        /// 默认值
        /// decimal
        public static decimal ToDecimal(object obj, int d = 0, bool isEnter = true, decimal def = 0)
        {
            if (obj == null)
            {
                return def;
            }
            else
            {
                try
                {
                    decimal n = Convert.ToDecimal(obj);//转换为decimal
                    if (isEnter)
                        return decimal.Round(n, d, MidpointRounding.AwayFromZero);//四舍五入
                    return Math.Truncate(n * (decimal)Math.Pow(10, d)) / (decimal)Math.Pow(10, d);//截取小数位数,不舍入
                }
                catch
                {
                    return def;
                }
            }
        }
        //string
        public static string ToString(object obj, string def = "")
        {
            if (obj == null)
            {
                return def;
            }
            else
            {
                try
                {
                    return Convert.ToString(obj);
                }
                catch
                {
                    return def;
                }
            }
        }
        //int32
        public static int ToInt32(object obj, int defaultValue = 0)
        {
            return ToInt(obj, defaultValue);
        }
        //int
        public static int ToInt(object obj, int defaultValue = 0)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt32(obj);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        //ToInt64 
        public static long ToInt64(object obj, long defaultValue = 0L)
        {
            return ToLong(obj, defaultValue);
        }
        //ToLong
        public static long ToLong(object obj, long defaultValue = 0L)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt64(obj);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        //ToInt16 
        public static short ToInt16(object obj, short defaultValue = 0)
        {
            return ToShort(obj, defaultValue);
        }
        //ToShort
        public static short ToShort(object obj, short defaultValue = 0)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToInt16(obj);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        //ToDouble
        public static double ToDouble(object obj, double defaultValue = 0D)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToDouble(obj);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        //ToFloat
        public static float ToFloat(object obj, float defaultValue = 0F)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return float.Parse(obj.ToString());
                }
                catch
                {
                    return defaultValue;
                }
            }
        }
        //ToBool
        public static bool ToBool(object obj, bool defaultValue = false)
        {
            if (obj == null)
            {
                return defaultValue;
            }
            else
            {
                try
                {
                    return Convert.ToBoolean(obj);
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        /// 
        /// List的分页
        /// 
        /// 实体类型
        /// List的数据集
        /// 总记录数
        /// 当前页码
        /// 每页条目数
        /// 分页后的List
        public static List ListPage(List list, out int total, int pageIndex = 1, int pageSize = 20)
        {
            total = list.Count;//总记录数
            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();//分页
        }
        /// 
        /// DataTable分页
        /// 
        /// DataTable
        /// 总记录数
        /// 页索引,注意:从1开始
        /// 每页大小
        /// 分好页的DataTable数据第1页   每页10条
        public static DataTable GetPagedTable(DataTable dt, out int total, int pageIndex = 1, int pageSize = 20)
        {
            total = 0;//总记录数

            if (pageIndex == 0) { return dt; }

            total = dt.Rows.Count;//总记录数

            DataTable newdt = dt.Copy();
            newdt.Clear();

            int rowbegin = (pageIndex - 1) * pageSize;
            int rowend = pageIndex * pageSize;

            if (rowbegin >= dt.Rows.Count) { return newdt; }

            if (rowend > dt.Rows.Count) { rowend = dt.Rows.Count; }

            for (int i = rowbegin; i <= rowend - 1; i++)
            {
                DataRow newdr = newdt.NewRow();
                DataRow dr = dt.Rows[i];
                foreach (DataColumn column in dt.Columns)
                {
                    newdr[column.ColumnName] = dr[column.ColumnName];
                }
                newdt.Rows.Add(newdr);
            }
            return newdt;
        }

        /// 
        /// 返回分页的页数
        /// 
        /// 总条数
        /// 每页显示多少条
        /// 如果 结尾为0:则返回1
        public static int PageCount(int total, int pageSize = 20)
        {
            int page = 0;
            if (total % pageSize == 0) { page = total / pageSize; }
            else { page = (total / pageSize) + 1; }
            if (page == 0) { page += 1; }
            return page;
        }

        /// 
        /// 判断字符串是否包含:
        /// 数字+字母(+特殊符号)
        /// 
        /// 字符串
        /// 是否包含符号
        /// 
        public static bool IsNumericLetter(string oldStr, bool booSign = true)
        {
            char[] arrNum = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            char[] arrLower = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
            char[] arrUpper = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
            char[] arrSign = { '`', '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', '{', ']', '}', ';', ':', ';', '\\', '|', ',', '<', '.', '>', '/', '?' };

            char[] arrTemp = oldStr.ToCharArray();

            if (IsMatch(arrTemp, arrNum))//是否包含数字
            {
                if (IsMatch(arrTemp, arrLower))//是否包含小写字母
                {
                    if (IsMatch(arrTemp, arrUpper))//是否包含大写字母
                    {
                        if (booSign)//需要判断符号吗?需要
                        {
                            if (IsMatch(arrTemp, arrSign))//是否包含符号
                            {
                                return true;
                            }
                        }
                        else//不需要
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
        public static bool IsMatch(char[] arr1, char[] arr2)
        {
            for (int i = 0; i < arr1.Length; i++)
            {
                for (int j = 0; j < arr2.Length; j++)
                {
                    if (arr1[i] == arr2[j])//只要有1个匹配,就返回true
                    {
                        return true;
                    }
                }
            }
            return false;//没有匹配的
        }

        /// 
        /// 时间戳
        /// 
        /// 
        public static long GetTimestamp()
        {
            return GetTimestamp(DateTime.Now);
        }
        public static long GetTimestamp(DateTime dt)
        {
            TimeSpan mTimeSpan = dt.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            long time = (long)mTimeSpan.TotalSeconds;
            return time;
        }

        /// 
        /// 生成指定长度的随机字符串
        /// (包含数字+大小写字母,不包含特殊符号)
        /// 
        /// 随机字符串长度
        /// 
        public static string GetRandomizer(int intLength)
        {
            return GetRandomizer(intLength, true, false, true, true);//包含数字+大小写字母,不包含特殊符号
        }
        /// 
        /// 生成指定长度的随机字符串
        /// 
        /// 随机字符串长度
        /// 生成的字符串中是否包含数字
        /// 生成的字符串中是否包含符号
        /// 生成的字符串中是否包含小写字母
        /// 生成的字符串中是否包含大写字母
        /// 
        public static string GetRandomizer(int intLength, bool booNumber, bool booSign, bool booSmallword, bool booBigword)
        {
            //定义  
            Random ranA = new Random();
            int intResultRound = 0;
            int intA = 0;
            string strB = "";

            while (intResultRound < intLength)
            {
                //生成随机数A,表示生成类型  
                //1=数字,2=符号,3=小写字母,4=大写字母  

                intA = ranA.Next(1, 5);

                //如果随机数A=1,则运行生成数字  
                //生成随机数A,范围在0-10  
                //把随机数A,转成字符  
                //生成完,位数+1,字符串累加,结束本次循环  

                if (intA == 1 && booNumber)
                {
                    intA = ranA.Next(0, 10);
                    strB = intA.ToString() + strB;
                    intResultRound = intResultRound + 1;
                    continue;
                }

                //如果随机数A=2,则运行生成符号  
                //生成随机数A,表示生成值域  
                //1:33-47值域,2:58-64值域,3:91-96值域,4:123-126值域  

                if (intA == 2 && booSign == true)
                {
                    intA = ranA.Next(1, 5);

                    //如果A=1  
                    //生成随机数A,33-47的Ascii码  
                    //把随机数A,转成字符  
                    //生成完,位数+1,字符串累加,结束本次循环  

                    if (intA == 1)
                    {
                        intA = ranA.Next(33, 48);
                        strB = ((char)intA).ToString() + strB;
                        intResultRound = intResultRound + 1;
                        continue;
                    }

                    //如果A=2  
                    //生成随机数A,58-64的Ascii码  
                    //把随机数A,转成字符  
                    //生成完,位数+1,字符串累加,结束本次循环  

                    if (intA == 2)
                    {
                        intA = ranA.Next(58, 65);
                        strB = ((char)intA).ToString() + strB;
                        intResultRound = intResultRound + 1;
                        continue;
                    }

                    //如果A=3  
                    //生成随机数A,91-96的Ascii码  
                    //把随机数A,转成字符  
                    //生成完,位数+1,字符串累加,结束本次循环  

                    if (intA == 3)
                    {
                        intA = ranA.Next(91, 97);
                        strB = ((char)intA).ToString() + strB;
                        intResultRound = intResultRound + 1;
                        continue;
                    }

                    //如果A=4  
                    //生成随机数A,123-126的Ascii码  
                    //把随机数A,转成字符  
                    //生成完,位数+1,字符串累加,结束本次循环  

                    if (intA == 4)
                    {
                        intA = ranA.Next(123, 127);
                        strB = ((char)intA).ToString() + strB;
                        intResultRound = intResultRound + 1;
                        continue;
                    }

                }

                //如果随机数A=3,则运行生成小写字母  
                //生成随机数A,范围在97-122  
                //把随机数A,转成字符  
                //生成完,位数+1,字符串累加,结束本次循环  

                if (intA == 3 && booSmallword == true)
                {
                    intA = ranA.Next(97, 123);
                    strB = ((char)intA).ToString() + strB;
                    intResultRound = intResultRound + 1;
                    continue;
                }

                //如果随机数A=4,则运行生成大写字母  
                //生成随机数A,范围在65-90  
                //把随机数A,转成字符  
                //生成完,位数+1,字符串累加,结束本次循环  

                if (intA == 4 && booBigword == true)
                {
                    intA = ranA.Next(65, 89);
                    strB = ((char)intA).ToString() + strB;
                    intResultRound = intResultRound + 1;
                    continue;
                }
            }
            return strB;
        }

        /*
         public enum TestEnum
        {
            Value1 = 1,
            Value2 = 2,
            Value3 = 3
        }
         */
        /// 
        /// 根据枚举的sting值获取对应的枚举值
        /// TestEnum reqValue = GetEnumValue("Value1");  // Output: Value1
        /// 
        /// 
        /// 
        /// 
        /// 
        public static T GetEnumValue(string str) where T : struct, IConvertible
        {
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new Exception("T must be an Enumeration type.");
            }
            T val;
            return Enum.TryParse(str, true, out val) ? val : default(T);
        }
        /// 
        /// 根据枚举的int值获得对应枚举
        /// TestEnum reqValue2 = GetEnumValue(2);// OutPut: Value2
        /// 
        /// 
        /// 
        /// 
        /// 
        public static T GetEnumValue(int intValue) where T : struct, IConvertible
        {
            Type enumType = typeof(T);
            if (!enumType.IsEnum)
            {
                throw new Exception("T must be an Enumeration type.");
            }

            return (T)Enum.ToObject(enumType, intValue);
        }

你可能感兴趣的:(笔记)