-4

I have this code that shows some build info in an About box:

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();
}

It appears like this today:

enter image description here

The "problem" is that screen real estate is limited, and dates such as "February 04, 2015" look geekish to me (I prefer "February 4, 2015").

I could kludgily brute-force the string returned from ToLongDateString() like so:

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

(I'm using "+=" because lblLastBuilt is set to "Last built " at design-time.

So: is there a less brute-forcish way to prevent leading 0s from appearing in the "day of month" portion of the date string?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

6

Use a custom format. (MMMM d, yyyy)

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

single d would give you a single or double digit day part. If the day part is below 10, then you will get only a single digit instead of leading 0, for others you will get both digits.

See: Custom Date and Time Format Strings

I prefer "February 4, 2015"

EDIT: I missed the part for day of week, I am not sure whether you need that or not but if you have to then you can add dddd in the custom format like:

dddd, MMMM d, yyyy
Habib
  • 219,104
  • 29
  • 407
  • 436
1

Try this:

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

It outputs, e.g. "Wednesday, February 4, 2015" using a custom date format.

rory.ap
  • 34,009
  • 10
  • 83
  • 174