C#: Code Optimization for Date Formatting

Using C#, I am trying to populate a variable with a known filename + date. The catch is that the date must always be the last day of the previous month. It must also have no slashes or hyphens, and the year must be two digits. For example, if it is now November 27 2015, I need my filename to be: Foobar_103115.txt

As a programmer who still has much to learn, I have written the clunky code below and it does achieve my desired result, even though it will obviously break after the end of this century. My code is written this way because I could not figure out a more direct syntax for getting the date I want, complete with the specified formatting.

My question is this: What would be a more elegant and efficient way of recreating the below code?

I have commented all the code for any novice programmers who might be interested in this. I know the experts I'm asking for help from don't need it.

public void Main()
{
    String Filename
    DateTime date = DateTime.Today;

    var FirstDayOfThisMonth = DateTime.Today.AddDays(-(DateTime.Today.Day - 1)); //Gets the FIRST DAY of each month
    var LastDayOfLastMonth = FirstDayOfThisMonth.AddDays(-1); //Subtracts one day from the first day of each month to give you the last day of the previous month

    String outputDate = LastDayOfLastMonth.ToShortDateString(); //Reformats a long date string to a shorter one like 01/01/2015
    var NewDate = outputDate.Replace("20", ""); //Gives me a two-digit year which will work until the end of the century
    var NewDate2 = NewDate.Replace("/", ""); //Replaces the slashes with nothing so the format looks this way: 103115 (instead of 10/31/15)

    Filename = "Foobar_" + NewDate2 + ".txt"; //concatenates my newly formatted date to the filename and assigns to the variable
Jon Skeet
people
quotationmark

Sounds like you want something more like:

// Warning: you should think about time zones...
DateTime today = DateTime.Today;
DateTime startOfMonth = new DateTime(today.Year, today.Month, 1);
DateTime endOfPreviousMonth = startOfMonth.AddDays(-1);
string filename = string.Format(CultureInfo.InvariantCulture,
    "FooBar_{0:MMddyy}.txt", endOfPreviousMonth);

I definitely wouldn't use ToShortDateString here - you want a very specific format, so express it specifically. The results of ToShortDateString will vary based on the current thread's culture.

Also note how my code only evaluates DateTime.Today once - this is a good habit to get into, as otherwise if the clock "ticks" into the next day between two evaluations of DateTime.Today, your original code could give some pretty odd results.

people

See more on this question at Stackoverflow