分类: C/C++
2012-09-24 18:14:16
#region 日期格式转换
///
/// 将数字表示的日期转换诚中文日期
///
///
///
private static string ConvertStringToChinese(string date)
{
string [] str = date.Split('年', '月', '日');
StringBuilder sb = new StringBuilder();
sb.Append(ConvertYear(str[0]));
sb.Append("年");
sb.Append(ConvertMonthorDay(str[1]));
sb.Append("月");
sb.Append(ConvertMonthorDay(str[2]));
sb.Append("日");
return sb.ToString();
}
///
/// 转换日期的月或日的部分
///
///
///
private static string ConvertMonthorDay(string date)
{
int num = int.Parse(date);
if (num<10)
{
return NumToChinese(num);
}
else if (num == 10)
{
return "十";
}
else if (num > 10 && num < 20)
{
return "十" + NumToChinese(num % 10);
}
else if (num == 20)
{
return "二十";
}
else if (num > 20 && num < 30)
{
return "二十" + NumToChinese(num % 10);
}
else if (num == 30)
{
return "三十";
}
else
{
return "三十一";
}
}
///
/// 讲数字转换成对应的汉字
///
///
///
private static string NumToChinese(int num)
{
string ch = string.Empty;
switch (num)
{
case 0:
ch = "零";
break;
case 1:
ch = "一";
break;
case 2:
ch = "二";
break;
case 3:
ch = "三";
break;
case 4:
ch = "四";
break;
case 5:
ch = "五";
break;
case 6:
ch = "六";
break;
case 7:
ch = "七";
break;
case 8:
ch = "八";
break;
case 9:
ch = "九";
break;
}
return ch;
}
///
/// 转换日期的年部分
///
///
///
private static string ConvertYear(string date)
{
char[] chYear = date.ToCharArray();
for (int i = 0; i < chYear.Length; i++)
{
switch (chYear[i])
{
case '0':
chYear[i] = '零';
break;
case '1':
chYear[i] = '一';
break;
case '2':
chYear[i] = '二';
break;
case '3':
chYear[i] = '三';
break;
case '4':
chYear[i] = '四';
break;
case '5':
chYear[i] = '五';
break;
case '6':
chYear[i] = '六';
break;
case '7':
chYear[i] = '七';
break;
case '8':
chYear[i] = '八';
break;
case '9':
chYear[i] = '九';
break;
default:
break;
}
}
return new string(chYear);
}
#endregion
====================================================
#region 日期转换
string date = "2012年12月31日";
date = ConvertStringToChinese(date);
Console.WriteLine(date);
Console.ReadKey();
#endregion
个人网站