以特定日期格式开始 ID 号

  • 本文关键字:开始 ID 格式 日期 c#
  • 更新时间 :
  • 英文 :


假设我有这个ID号,开头是:911125...

91 = 1991(年)
11 = 11月(月)
25 = 天(天)

我怎样才能得到这个格式:1991年11月25日?

编辑:这是我尝试过的,但我知道这是错误的:

DateTime dt = DateTime.ParseExact(dateOfBirth, "yyMMdd", CultureInfo.InvariantCulture);
你需要

把它解析为DateTime对象(DateTime.TryParseExact),然后你可以像这样格式化它:

string str = "911125";
DateTime dt;
if (DateTime.TryParseExact(str
                            , "yyMMdd"
                            , CultureInfo.InvariantCulture
                            , DateTimeStyles.None
                            , out dt))
{
    Console.WriteLine(dt.ToString("dd MMMM yyyy"));
}
else
{
    Console.WriteLine("Invalid date string");
}

您将获得:

25 November 1991

编辑:

您的代码应该可以正常工作,它正在解析Date,但您没有格式化它以进行显示。

string formattedDate = dt.ToString("dd MMMM yyyy");

我使用 DateTime.TryParseExact 的原因是,如果解析失败,它不会引发异常。 DateTime.ParseExact将执行相同的工作,但如果传递给它的字符串与提供的格式不匹配,它会引发异常。

最新更新