Bali C
Bali C

Reputation: 31251

Convert DateTime.Now to a valid Windows filename

I have had this issue quite a few times and have just been using a workaround but thought I would ask here in case there is an easier option. When I have a string from DateTime.Now and I then want to use this in a filename I can't because Windows doesn't allow the characters / and : in filenames, I have to go and replace them like this:

string filename = DateTime.Now.ToString().Replace('/', '_').Replace(':', '_');

Which seems a bit of a hassle, is there an easier way to do this? Any suggestions much appreciated.

Upvotes: 43

Views: 33634

Answers (5)

Samich
Samich

Reputation: 30175

Use a ToString pattern:

DateTime.Now.ToString("yyyy-MM-dd-HH-mm") // will produce 2011-10-24-13-10

Upvotes: 11

inwenis
inwenis

Reputation: 407

If you need the datetime to be more precise you can use:

DateTime.Now.ToString("O").Replace(":", "_") //2016-09-21T13_14_01.3624587+02_00

or (if you need a little less)

DateTime.Now.ToString("s").Replace(":", "_") //2016-09-21T13_16_11

Both are valid file names and are sortable.

You can create an extensions method:

public static string ToFileName(this DateTime @this)
{
    return @this.ToString("O").Replace(":", "_");
}

And then use it like this:

var saveZipToFile = "output_" + DateTime.Now.ToFileName() + ".zip";

The "s" format does not take time zones into account and thus the datetimes:

  • 2014-11-15T18:32:17+00:00
  • 2014-11-15T18:32:17+08:00

formatted using "s" are identical.

So if your datetimes represent dirrerent time zones I would recommend using "O" or using DateTime.UtcNow.

Upvotes: 3

xanatos
xanatos

Reputation: 111940

As written by Samich, but

// The following will produce 2011-10-24-13-10
DateTime.Now.ToString("yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture);

If you don't trust me, try setting the culture to new CultureInfo("ar-sa"); :-)

I'll add that, if you hate the world, this is the most precise thing to do:

DateTime.Now.Ticks.ToString("D19");

There are 19 digits in DateTime.MaxValue.Ticks

If you hate the world even more:

DateTime.Now.Ticks.ToString("X16");

There are 16 hex digits in DateTime.MaxValue.Ticks.

Upvotes: 53

BigMike
BigMike

Reputation: 6873

You can use timestamp's long format:

DateTime.Now.ToBinary()

Upvotes: 2

Royi Namir
Royi Namir

Reputation: 148744

 DateTime.Now.ToString("dd_MM_yyyy")

Upvotes: 59

Related Questions