从日期的 day-of-month 部分去除前导 0 的最干净方法是什么?

What is the cleanest way to strip leading 0s from the day-of-month portion of dates?

我有这段代码可以在“关于”框中显示一些构建信息:

private void frmAbout_Load(object sender, EventArgs e)
{
    Version versionInfo =
        Assembly.GetExecutingAssembly().GetName().Version;
    lblVersion.Text = String.Format("Version {0}.{1}", 
        versionInfo.Major.ToString(), versionInfo.Minor.ToString());
    String versionStr = String.Format("{0}.{1}.{2}.{3}", 
        versionInfo.Major.ToString(), versionInfo.Minor.ToString(), 
        versionInfo.Build.ToString(), versionInfo.Revision.ToString());
    lblBuild.Text = String.Format("Build {0}", versionStr);

    DateTime startDate = new DateTime(2000, 1, 1); // The date from 
        whence the Build number is incremented (each day, not each 
        build; see    
        i-get-the-build-number-of-a-visual-studio-project-to-increment)
    int diffDays = versionInfo.Build;
    DateTime computedDate = startDate.AddDays(diffDays);
    lblLastBuilt.Text += computedDate.ToLongDateString();
}

今天看起来是这样的:

"problem" 是屏幕空间有限,"February 04, 2015" 这样的日期对我来说看起来很怪异(我更喜欢 "February 4, 2015")。

我可以像这样 brute-force 从 ToLongDateString() 返回的字符串:

String lds = computedDate.ToLongDateString();
lds = // find leading 0 in date and strip it out or replace it with an empty string
lblLastBuilt += lds;

(我使用“+=”是因为 lblLastBuilt 在 design-time 处设置为 "Last built "。

那么:是否有一种 less brute-forcish 方法来防止前导 0 出现在日期字符串的 "day of month" 部分?

使用自定义格式。 (MMMM d, yyyy)

String lds = computedDate.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture);

d 会给你一个单位数或两位数的天部分。如果日部分低于 10,那么您将只得到一个数字而不是前导 0,对于其他人,您将得到两个数字。

参见:Custom Date and Time Format Strings

I prefer "February 4, 2015"

编辑:我错过了星期几的部分,我不确定你是否需要,但如果你需要,你可以在自定义格式中添加 dddd,例如:

dddd, MMMM d, yyyy

试试这个:

computedDate.ToString("dddd, MMMM d, yyyy");

它输出,例如"Wednesday, February 4, 2015" 使用 custom date format.