C#helper类将日期转换为单词,如果有兴趣的也可以自己实现汉语的版本,具体代码如下
public static class DateToWords
{
private static CultureInfo ci = new CultureInfo("en-US");
private static string[] unitsMap = new string[]
{ "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen" };
private static string[] tensMap = new string[]
{ "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
//https://stackoverflow.com/questions/2729752/converting-numbers-in-to-words-c-sharp
private static string NumberToWords(int number)
{
if (number == 0)
return "zero";
string words = "";
if ((number / 1000) > 0)
{
words += NumberToWords(number / 1000) + " Thousand ";
number %= 1000;
}
if ((number / 100) > 0)
{
words += NumberToWords(number / 100) + " Hundred ";
number %= 100;
}
if (number > 0)
{
if (words != "")
words += " ";
if (number < 20)
words += unitsMap[number];
else
{
words += tensMap[number / 10];
if ((number % 10) > 0)
words += " " + unitsMap[number % 10];
}
}
return Regex.Replace(words, @"\ {2,}", " ");
}
public static string Convert(DateTime dt)
{
//convert days
string dtw = NumberToWords(dt.Day);
//convert months
dtw += " " + dt.ToString("MMMM", ci);
//convert years
dtw += ", " + NumberToWords(dt.Year);
return dtw;
}
}
使用如下(控制台应用程序为例)
void Main()
{
DateTime[] dates = new DateTime[]
{
new DateTime(1981, 1, 28),
new DateTime(1998, 2, 1),
new DateTime(2000, 3, 31),
new DateTime(2001, 4, 8),
new DateTime(2016, 6, 5),
new DateTime(1977, 8, 3),
new DateTime(2012, 10, 12),
new DateTime(1968, 12, 15)
};
foreach(DateTime dt in dates)
{
string dtw = DateToWords.Convert(dt);
Console.WriteLine("{0} => '{1}'", dt.ToString("dd-MM-yyyy"), dtw);
}
Console.ReadKey();
}
结果如下:
28-01-1981 => 'Twenty Eight January, One Thousand Nine Hundred Eighty One'
01-02-1998 => 'One February, One Thousand Nine Hundred Ninety Eight'
31-03-2000 => 'Thirty One March, Two Thousand '
08-04-2001 => 'Eight April, Two Thousand One'
05-06-2016 => 'Five June, Two Thousand Sixteen'
03-08-1977 => 'Three August, One Thousand Nine Hundred Seventy Seven'
12-10-2012 => 'Twelve October, Two Thousand Twelve'
15-12-1968 => 'Fifteen December, One Thousand Nine Hundred Sixty Eight'