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

        public static DateTime? ToDateTime(object obj)
        {
            if (obj == null)
            {
                return null;
            }
            else
            {
                try
                {
                    return Convert.ToDateTime(obj);
                }
                catch
                {
                    return null;
                }
            }
        }
        /// <summary>
        /// 日期格式化
        /// </summary>
        /// <param name="dt">日期(可为Null)</param>
        /// <param name="format">日期格式化的格式(默认值'年月日',缺省值'年月日时分秒')</param>
        /// <param name="defNow">日期为Null时是否用Now代替?</param>
        /// <returns></returns>
        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 "";
            }
        }

        /// <summary>
        /// 取得某月的第一天
        /// </summary>
        /// <param name="datetime">要取得月份第一天的时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day);
        }
        /// <summary>
        /// 取得某月的最后一天
        /// </summary>
        /// <param name="datetime">要取得月份最后一天的时间</param>
        /// <returns></returns>
        private DateTime LastDayOfMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1).AddDays(-1);
        }
        /// <summary>
        /// 取得上个月第一天
        /// </summary>
        /// <param name="datetime">要取得上个月第一天的当前时间</param>
        /// <returns></returns>
        private DateTime FirstDayOfPreviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(-1);
        }
        /// <summary>
        /// 取得上个月的最后一天
        /// </summary>
        /// <param name="datetime">要取得上个月最后一天的当前时间</param>
        /// <returns></returns>
        private DateTime LastDayOfPrdviousMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddDays(-1);
        }
        /// <summary>
        /// 取得下个月的第一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        private DateTime FirstDayOfNextMonth(DateTime datetime)
        {
            return datetime.AddDays(1 - datetime.Day).AddMonths(1);
        }
        /// <summary>
        /// 取得下个月的最后一天
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        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
        }
        /// <summary>
        /// object转decimal
        /// </summary>
        /// <param name="obj">obj</param>
        /// <param name="d">小数位数</param>
        /// <param name="isEnter">是否四舍五入</param>
        /// <param name="def">默认值</param>
        /// <returns>decimal</returns>
        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;
                }
            }
        }

        /// <summary>
        /// List<T>的分页
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="list">List<T>的数据集</param>
        /// <param name="total">总记录数</param>
        /// <param name="pageIndex">当前页码</param>
        /// <param name="pageSize">每页条目数</param>
        /// <returns>分页后的List<T></returns>
        public static List<T> ListPage<T>(List<T> list, out int total, int pageIndex = 1, int pageSize = 20)
        {
            total = list.Count;//总记录数
            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList<T>();//分页
        }
        /// <summary>
        /// DataTable分页
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <param name="total">总记录数</param>
        /// <param name="pageIndex">页索引,注意:从1开始</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns>分好页的DataTable数据</returns>第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;
        }

        /// <summary>
        /// 返回分页的页数
        /// </summary>
        /// <param name="total">总条数</param>
        /// <param name="pageSize">每页显示多少条</param>
        /// <returns>如果 结尾为0:则返回1</returns>
        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;
        }

        /// <summary>
        /// 判断字符串是否包含:
        /// 数字+字母(+特殊符号)
        /// </summary>
        /// <param name="oldStr">字符串</param>
        /// <param name="booSign">是否包含符号</param>
        /// <returns></returns>
        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;//没有匹配的
        }

        /// <summary>
        /// 时间戳
        /// </summary>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 生成指定长度的随机字符串
        /// (包含数字+大小写字母,不包含特殊符号)
        /// </summary>
        /// <param name="intLength">随机字符串长度</param>
        /// <returns></returns>
        public static string GetRandomizer(int intLength)
        {
            return GetRandomizer(intLength, true, false, true, true);//包含数字+大小写字母,不包含特殊符号
        }
        /// <summary>
        /// 生成指定长度的随机字符串
        /// </summary>
        /// <param name="intLength">随机字符串长度</param>
        /// <param name="booNumber">生成的字符串中是否包含数字</param>
        /// <param name="booSign">生成的字符串中是否包含符号</param>
        /// <param name="booSmallword">生成的字符串中是否包含小写字母</param>
        /// <param name="booBigword">生成的字符串中是否包含大写字母</param>
        /// <returns></returns>
        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
        }
         */
        /// <summary>
        /// 根据枚举的sting值获取对应的枚举值
        /// TestEnum reqValue = GetEnumValue<TestEnum>("Value1");  // Output: Value1
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static T GetEnumValue<T>(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<T>(str, true, out val) ? val : default(T);
        }
        /// <summary>
        /// 根据枚举的int值获得对应枚举
        /// TestEnum reqValue2 = GetEnumValue<TestEnum>(2);// OutPut: Value2
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="intValue"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static T GetEnumValue<T>(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);
        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值