C#:日期格式的代码优化

时间:2015-11-27 21:36:58

标签: c# date-formatting

使用C#,我试图填充一个已知文件名+日期的变量。问题是日期必须始终是上个月的最后一天。它也必须没有斜线或连字符,年份必须是两位数。例如,如果它现在是2015年11月27日,我需要我的文件名:Foobar_103115.txt

作为一名仍然需要学习的程序员,我已经在下面编写了笨重的代码并且它确实达到了我想要的结果,即使它在本世纪末之后显然会破裂。我的代码是以这种方式编写的,因为我无法找到更直接的语法来获取我想要的日期,并完成指定的格式。

我的问题是:重新创建以下代码的更优雅和有效的方法是什么?

我已经评论过任何可能对此感兴趣的新手程序员的所有代码。我知道我要求帮助的专家不需要它。

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

1 个答案:

答案 0 :(得分:9)

听起来你想要更像的东西:

// 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);

我绝对不会在这里使用ToShortDateString - 您需要一种非常具体的格式,因此请特别表达。 ToShortDateString的结果将根据当前线索的文化而有所不同。

另请注意我的代码只评估DateTime.Today一次 - 这是一个很好的习惯,如果时钟"滴答"在DateTime.Today的两次评估之间的第二天,您的原始代码可能会给出一些非常奇怪的结果。