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

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:

Debug.WriteLine(DateTime.Now.ToString()); // <-- 9/19/2012 1:41:46 PM
Debug.WriteLine(DateTime.Now.ToShortTimeString()); // <-- 1:41 PM
Debug.WriteLine(DateTime.Now.ToShortDateString()); // <-- 9/19/2012
Debug.WriteLine(DateTime.Now.ToFileTime()); // <-- 129925501061462806

ToFileTime() works but is not exactly human-readable. How can I format the output to a human-readable timestamp with date and time that can be used in a filename or extension? Prefereably something like 2011-19-9--13-45-30?


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.