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

半城伤御伤魂 提交于 2019-11-28 16:46:45

You can use this:

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");

I would use the ISO 8601 format, without separators:

DateTime.Now.ToString("yyyyMMddTHHmmss")

I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with

DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35

When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.

The below list of time format specifiers most commonly used.,

dd -- day of the month, from 01 through 31.

MM -- month, from 01 through 12.

yyyy -- year as a four-digit number.

hh -- hour, using a 12-hour clock from 01 to 12.

mm -- minute, from 00 through 59.

ss -- second, from 00 through 59.

HH -- hour, using a 24-hour clock from 00 to 23.

tt -- AM/PM designator.

Using the above you will be able to form a unique name to your file name.

Here i have provided example

string fileName = "fileName_" + DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss-tt") + ".pdf";

OR

If you don't prefer to use symbols you can try this also.,

string fileName = "fileName_" + DateTime.Now.ToString("MMddyyyyhhmmsstt") + ".pdf";

Hope this helps to someone now or in future. :)

Personally I like it this way:

DateTime.Now.ToString("yyyy-MM-dd HH.mm.ss")

Because it distinguishes between the date and the time.

Aghilas Yakoub

You can try with

var result = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss");
rouhollah ghasempour

You can make a path for your file as bellow:

string path = "fileName-"+DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

Using interpolation string & format specifier:

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

Or if you're not in America:

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

This feature is available in C# 6 and later versions of the language.

user4833581

Try this:

time.ToLongDateString()

Output: "Friday, August 24, 2018"

or use formatting:

time.ToString("yyyy_MM_dd")

Output: "2018_08_24"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!