[c#] 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?

This question is related to c# datetime filenames datetime-format

The answer is


You can make a path for your file as bellow:

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

I would use the ISO 8601 format, without separators:

DateTime.Now.ToString("yyyyMMddTHHmmss")

You can try with

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

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.


Personally I like it this way:

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

Because it distinguishes between the date and the time.


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. :)


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to filenames

Rename multiple files in a folder, add a prefix (Windows) How to loop over files in directory and change path and add suffix to filename Why do I get a SyntaxError for a Unicode escape in my file path? Git copy file preserving history A html space is showing as %2520 instead of %20 How do I get the file name from a String containing the Absolute file path? DateTime.ToString() format that can be used in a filename or extension? Get only filename from url in php without any variable values which exist in the url Obtaining only the filename when using OpenFileDialog property "FileName" Build the full path filename in Python

Examples related to datetime-format

How do I convert 2018-04-10T04:00:00.000Z string to DateTime? Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8) How can I create basic timestamps or dates? (Python 3.4) Format Instant to String Laravel $q->where() between dates How to Convert datetime value to yyyymmddhhmmss in SQL server? AngularJS - convert dates in controller Display DateTime value in dd/mm/yyyy format in Asp.NET MVC Display date in dd/mm/yyyy format in vb.net Convert DataFrame column type from string to datetime, dd/mm/yyyy format