DateTime.ToString() format that can be used in a filename or extension?

前端 未结 8 2110
北恋
北恋 2020-12-12 16:53

I want to add a timestamp to filenames as files are created but most of the DateTime methods I\'ve tried output something with spaces and slashes. For instance:



        
8条回答
  •  难免孤独
    2020-12-12 17:17

    Using interpolation string & format specifier:

    var filename = $"{DateTime.Now:yyyy.dd.M HH-mm-ss}"
    

    Example Output for January 1st, 2020 at 10:40:45AM:

    2020.28.01 10-40-45


    Or if you want a standard date format:

    var filename = $"{DateTime.Now:yyyy.M.dd HH-mm-ss}"
    

    2020.01.28 10-40-45


    Note: this feature is available in C# 6 and later versions of the language.

提交回复
热议问题