从日期的日期部分中删除前导0的最简洁方法是什么?

时间:2015-02-04 18:53:58

标签: c# datetime text-parsing date-math date-manipulation

我有这个代码在关于框中显示一些构建信息:

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 http://stackoverflow.com/questions/27557023/how-can-   
        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();
}

今天看起来像这样:

enter image description here

"问题"是屏幕房地产是有限的,日期,如" 2015年2月4日和#34;对我来说看起来很怪异(我更喜欢" 2015年2月4日和#34;)。

我可以像这样粗暴地强制从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设置为"上次构建"在设计时。

所以:是否有一种不那么野蛮的方式来阻止领先的0出现在"月中"日期字符串的一部分?

2 个答案:

答案 0 :(得分:6)

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

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

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

请参阅:Custom Date and Time Format Strings

  

我更喜欢" 2015年2月4日"

编辑:我错过了星期几的部分,我不确定您是否需要,但如果必须,那么您可以添加dddd自定义格式,如:

dddd, MMMM d, yyyy

答案 1 :(得分:1)

试试这个:

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

它输出,例如“2015年2月4日星期三”使用custom date format