146

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?

pdizz
  • 4,100
  • 4
  • 28
  • 42

8 Answers8

214

You can use this:

DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss");
Kristof Claes
  • 10,797
  • 3
  • 30
  • 42
  • 5
    You have a look at more examples/options here: http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm – Kristof Claes Sep 19 '12 at 17:47
  • 2
    I guess considering utc time would be better – RealSteel Jun 07 '16 at 06:12
  • 182
    Are you seriously suggesting to have the day between the year and month?? – kjbartel Jun 20 '17 at 11:13
  • 23
    Even more inexcusable in a filename since the list of files cannot be sorted by name to get them in date time order. Most-significant to least significant should be the order of the day. – Bernhard Hofmann Mar 16 '18 at 12:19
  • @Bernhard Hofmann, you can sort the file names by created/modified attributes if you care so much about that. – Matt May 07 '18 at 18:52
  • 9
    @Matt - you assume the filename is related to the created/modified/accessed date which it isn't always. – Bernhard Hofmann May 11 '18 at 14:37
  • @Bernhard Hofmann, I was referring to the created/modified metadata stored for the file in the file system, not the file name itself: https://imgur.com/a/5xSAnbX – Matt May 11 '18 at 15:36
  • 6
    @Matt And now take that file, copy it to a USB stick to transfer somewhere else and then check that metadata again (apart from the obvious problem that Bernhard is talking about: You might create a file for a date other than "right now"). It's just incredibly stupid to have this as the highest upvoted and accepted answer. – Voo Oct 10 '19 at 11:24
  • 6
    So we found our way here after discovering that a third-party pod running in our Kubernetes cluster was constantly writing files named e.g. `2022-31-1--13-37-42.txt` until disk space ran out. We concluded that such an, um, unorthodox date format simply _had_ to be explicitly specified in the source code of the pod, and sure enough: the culprit line used the exact expression above. Turns out this answer is the top result on Google for `date format file name dotnet` and similar queries, so if it was submitted as a honeypot to expose copy-paste programming, then well played! – Simon Alling Jan 31 '22 at 19:23
172

I would use the ISO 8601 format, without separators:

DateTime.Now.ToString("yyyyMMddTHHmmss")
Christoffer Lette
  • 14,346
  • 7
  • 50
  • 58
  • 8
    If you use `DateTime.Now.ToString("o")`, it will give you `yyyy-MM-ddTHH:mm:ss.fffffff-HH:mm` (where the final hour and minute offset are +/- GMT). Granted, this wouldn't work as a filename format, but the `"o"` formatting is good to know. – krillgar Sep 26 '14 at 19:18
  • 9
    This can also be written as `$"{DateTime.Now:yyyyMMddTHHmmss}"` using string interpolation. – Corbie Oct 01 '20 at 11:02
  • 2
    [RFC 3339](https://tools.ietf.org/html/rfc3339#section-5.6) Says that you should retain the dashes for date. `DateTime.Now.ToString("s").Replace(":", "")` – HackSlash Nov 24 '20 at 21:23
  • 1
    @HackSlash Good to know. This question, however, is about file names where we often need to consider illegal characters. `:` is often such a character (while `-` often is not). Then it becomes a question of whether to always use separators (possibly introducing illegal characters), use separators where possible (not compliant to standards) or skip separators completely (compliant). This answer clearly is in favor of the latter. – Christoffer Lette Nov 27 '20 at 13:21
  • @HackSlash Removing only the `:` will most likely result in a timestamp that is neither ISO8601 nor RFC3339 compliant. – Christoffer Lette Nov 27 '20 at 13:24
28

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.

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Gabe Haack
  • 536
  • 4
  • 7
14

Personally I like it this way:

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

Because it distinguishes between the date and the time.

Charles Clayton
  • 17,005
  • 11
  • 87
  • 120
  • 2
    I guess you mean "yyyy-MM-dd HH.mm.ss" – Filimindji Feb 12 '18 at 18:27
  • 4
    While this is valid, having spaces in file names/paths is generally not best, as it can introduce problems in software that doesn't account for that, and paths in the command line that don't contain quotes. Having an underscore or two dashes is better practice. – Noah Heber Sep 06 '20 at 02:48
  • @NoahHeber They really do not, except you are using Linux. Where everybody harps how great their OS is and how bullshit windows is. Except every second script or program cannot work with freaking spaces in a path. I rather like my spaces in a path, at least I value it more than the ability to write a file named COM1 – Christian Sauer Apr 03 '23 at 10:42
11

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

RajeshKdev
  • 6,365
  • 6
  • 58
  • 80
  • I would prefer using string interpolation: `var fileName = $"fileName_{DateTime.Now:MMddyyyyhhmmsstt}.pdf";` – Corbie Oct 01 '20 at 11:04
7

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.

ChickenFeet
  • 2,653
  • 22
  • 26
  • 1
    year-day-month is not a valid date format/order. There is only one date standard that starts with the year, and it's year-month-day order. month-day-year is OK in the US, but day-month-year isn't universal everywhere outside of the US either. – Jeremy Bell Nov 11 '20 at 15:29
  • @JeremyBell year-day-month is used because the question specifically asks for that format, "_Prefereably something like 2011-19-9--13-45-30_" – ChickenFeet Nov 17 '20 at 05:36
4

You can try with

var result = DateTime.Now.ToString("yyyy-MM-d--HH-mm-ss");
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
2

You can make a path for your file as bellow:

string path = "fileName-"+DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";
Moerwald
  • 10,448
  • 9
  • 43
  • 83