public static class StringExtensions { /// <summary> /// 转换为Int32 /// </summary> /// <param name="num"></param> /// <returns></returns> public static int ToInt32(this string num) { int i; return (!Int32.TryParse(num, out i)) ? i : 0; } /// <summary> /// 转换为双精度 /// </summary> /// <param name="num"></param> /// <returns></returns> public static double ToDouble(this string num) { double i; return (Double.TryParse(num, out i)) ? i : 0.0; } /// <summary> /// 获取MD5值 /// </summary> /// <param name="str">加密的字符串</param> /// <returns>返回MD5值</returns> public static string ToMd5(this string str) { return FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5"); } /// <summary> /// 将source转换为以sp分隔的数组 /// </summary> /// <param name="source"></param> /// <param name="sp"></param> /// <returns></returns> public static string[] SplitString(this string source, string sp) { return Regex.Split(source, sp, RegexOptions.IgnoreCase); } private static readonly DateTime nullDate = new DateTime(1900, 1, 1, 12, 0, 0); /// <summary> /// 字符串转为日期 /// </summary> /// <param name="str"></param> /// <returns></returns> public static DateTime ToDate(this string str) { return IsDate(str) ? DateTime.Parse(str) : nullDate; } /// <summary> /// 判断一个字符串是否是日期格式 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool IsDate(this string str) { if (String.IsNullOrEmpty(str)) return false; var r = new Regex(@"\d{4}([/-年])\d{1,2}([/-月])\d{1,2}([日])\s?\d{0,2}:?\d{0,2}:?\d{0,2}"); if(r.IsMatch(str)) { str = str.Replace("年", "-"); str = str.Replace("月", "-"); str = str.Replace("日", " "); str = str.Replace(" ", " "); DateTime dt; return DateTime.TryParse(str,out dt); } return false; } /// <summary> /// 转换为农历日期 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string GetChineseDate(this string str) { var dt = ToDate(str); return ToDate(str).DateDiff(nullDate, "day") != 0 ? dt.GetChineseDate() : ""; } /// <summary> /// 实现JS.Escape /// </summary> /// <param name="s"></param> /// <returns></returns> public static string Escape(this string s) { return String.IsNullOrEmpty(s) ? "" : Uri.EscapeUriString(s); } /// <summary> /// 实现JS.Escape /// </summary> /// <param name="s"></param> /// <returns></returns> public static string Unescape(this string s) { return String.IsNullOrEmpty(s) ? "" : Uri.UnescapeDataString(s); } }