如何将日期转换为字格式?

时间:2012-05-12 17:11:30

标签: c# asp.net datetime

我有一个像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 所以我想要一个类似“十二月二十二”的字符串

我该怎么做?

请帮帮我......

提前致谢....

4 个答案:

答案 0 :(得分:10)

您需要查看每个日期部分并使用函数来获取书面等效项。我在下面添加了一个将整数转换为书面文本的类,并将其扩展为支持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

答案 1 :(得分:2)

这不是您想要的,但我可以建议使用内置功能的最接近的是ToLongDateString,它会为您提供月份名称,并且显然对文化非常敏感。

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

答案 2 :(得分:1)

假设12/05/2012是一个字符串,那么你必须标记化它成为用斜杠“/”分隔的元素。 E.g:

  

“12/05/2012” - &gt; [“12”,“05”,“2012”]

接下来,您自己定义一个规则,将这些元素解析为您期望的内容。说,“12”是“十二”,“05”是“五”或“五月”等。

答案 3 :(得分:0)

string MyDate = "12/05/2012";
DateTime expected = Convert.ToDateTime(MyDate);
string MyNewDate = expected.ToString("dd MMM yyyy");

在此网站https://www.mikesdotnetting.com/article/23/date-formatting-in-c上检查其他日期格式。