2012-05-12 31 views
6

我有一个约会一样12/05/2012现在我想改变这种格式,以简单的字符串。如何将日期转换为文字格式?

为前。

string newdate = new string(); 
newdate = "12/05/2012"; 
DateTime Bdate = DateTime.ParseExact(Newdate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); 

现在我BDate是DateTime 即。 BDate= 2012/05/12

现在我想这样做

如果我的Bdate是12/05/2012 ,所以我想一个字符串,像类似的“十二五月二零一二年”

我该怎么办这个?

请帮我...

在此先感谢....

+0

请问为什么要这样做?这是相当不寻常的日期格式(而不是它应该是'五月十二,两千Twelve'?)。 –

+3

@FrédéricHamidi:只有在美国。在世界其他地方,我们将其称为“十二月五日”。这就是“MM/dd”与“dd/MM”差距的原因。 – Douglas

+0

@Douglas,啊,我明白了。感谢您的澄清:) –

回答

9

你需要看看每个日期部分,并使用一个函数来获取书面等同。我在下面列出的是一类整数转换成书面文字,并扩展其支持DateTime转换,以及:

public static class WrittenNumerics 
{ 
    static readonly string[] ones = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }; 
    static readonly string[] teens = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }; 
    static readonly string[] tens = new string[] { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" }; 
    static readonly string[] thousandsGroups = { "", " Thousand", " Million", " Billion" }; 

    private static string FriendlyInteger(int n, string leftDigits, int thousands) 
    { 
     if (n == 0) 
      return leftDigits; 

     string friendlyInt = leftDigits; 
     if (friendlyInt.Length > 0) 
      friendlyInt += " "; 

     if (n < 10) 
      friendlyInt += ones[n]; 
     else if (n < 20) 
      friendlyInt += teens[n - 10]; 
     else if (n < 100) 
      friendlyInt += FriendlyInteger(n % 10, tens[n/10 - 2], 0); 
     else if (n < 1000) 
      friendlyInt += FriendlyInteger(n % 100, (ones[n/100] + " Hundred"), 0); 
     else 
      friendlyInt += FriendlyInteger(n % 1000, FriendlyInteger(n/1000, "", thousands + 1), 0); 

     return friendlyInt + thousandsGroups[thousands]; 
    } 

    public static string DateToWritten(DateTime date) 
    { 
     return string.Format("{0} {1} {2}", IntegerToWritten(date.Day), date.ToString("MMMM"), IntegerToWritten(date.Year)); 
    } 

    public static string IntegerToWritten(int n) 
    { 
     if (n == 0) 
      return "Zero"; 
     else if (n < 0) 
      return "Negative " + IntegerToWritten(-n); 

     return FriendlyInteger(n, "", 0); 
    } 
} 

免责声明:基本功能礼貌的@Wedge

使用这个类,只需调用DateToWritten方法:

var output = WrittenNumerics.DateToWritten(DateTime.Today); 

以上的输出是:Twelve May Two Thousand Twelve

+0

感谢您的大力帮助.. :) –

1

这不是你想要的,但最接近我可以建议使用内置功能为ToLongDateString,它给你这个月的名字,显然对文化敏感。

string str = bdate.ToLongDateString(); 
// Assuming en-US culture, this would give: "Saturday, May 12, 2012" 
+0

我不需要这样。我想要十二月五月十二月 –

1

假设12/05/2012是一个字符串,那么你必须记号化成其分离的斜杠“/”的元素。例如:

“12/05/2012” - > [ “12”, “05”, “2012”]

接下来,你自己定义的,它解析这些元素,你的规则期望。说,“12”是“十二条”,“05”是“十二五”或“可以”等

+0

我认为将它们转换为书面数字是OP有麻烦... –

相关问题