/// <summary>
/// 清除html标记并截取前50个字符
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
protected string FormatStr(string str)
{
str = System.Text.RegularExpressions.Regex.Replace(str, "<[^>]+>", "");
str = str.Length > 50 ? str.Substring(0, 50) + "..." : str;
return str;
}
/// <summary>
/// 获取身份证的最后一位校验码
/// </summary>
/// <param name="pid"></param>
/// <returns></returns>
public string GetPIdVerifyCode(string pid)
{
int[] Wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
string[] arrVerifyCode = { "1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2" };
int ret = 0;
for (int i = 0; i < 17; i++)
ret += int.Parse(pid.Substring(0, 17).Substring(i, 1)) * Wi[i];
return arrVerifyCode[ret %= 11];
}
/// <summary>
/// 获取随机数实例Random
/// </summary>
/// <returns></returns>
public static Random GetRandom()
{
Guid guid = Guid.NewGuid();
int key1 = guid.GetHashCode();
int key2 = unchecked((int)DateTime.Now.Ticks);
int seed = unchecked(key1 * key2);
Random rand = new Random(seed);
return rand;
}
/// <summary>
/// yyyy-mm-dd转换为yyyymmdd
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static string ConvertDateToString(string strDate)
{
return DateTime.ParseExact(strDate, "yyyy-MM-dd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyyMMdd");
}
/// <summary>
/// yyyymmdd转换为yyyy-mm-dd
/// </summary>
/// <param name="strDate"></param>
/// <returns></returns>
public static string ConvertStringToDate(string strDate)
{
return DateTime.ParseExact(strDate, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");
}
/// <summary>
/// 截取中英文字符串(英文算1个长度,中文算2个长度)
/// </summary>
public static string bSubstr(this string input, int index, int len)
{
Encoding encode = Encoding.GetEncoding("gb2312");
byte[] byteArr = encode.GetBytes(input);
if (byteArr.Length <= len) return input;
int m = 0, n = 0;
foreach (byte b in byteArr)
{
if (n >= len) break;
if (b > 127) m++; //重要一步:对前p个字节中的值大于127的字符进行统计
n++;
}
if (m % 2 != 0) n = len + 1; //如果非偶:则说明末尾为双字节字符,截取位数加1
return encode.GetString(byteArr, index, n);
}
/// <summary>
/// 获取两个日期之间的月的个数
/// </summary>
/// <param name="startDate"></param>
/// <param name="endDate"></param>
/// <returns></returns>
public static int GetTotalMonths(DateTime startDate, DateTime endDate)
{
int totalMonths = endDate.Year * 12 + endDate.Month - startDate.Year * 12 - startDate.Month + 1;
return totalMonths;
}
c#一些函数
最新推荐文章于 2024-01-30 13:24:07 发布