簡體   English   中英

C#:日期格式的代碼優化

[英]C#: Code Optimization for 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

聽起來您想要更多類似的東西:

// 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評估之間第二天時鍾“滴答”,您的原始代碼可能會給出一些非常奇怪的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM