Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
Bali C Avatar asked Oct 24 '11 10:10

Bali C


4 Answers

 DateTime.Now.ToString("dd_MM_yyyy")
like image 186
Royi Namir Avatar answered Oct 11 '22 15:10

Royi Namir


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.

like image 42
xanatos Avatar answered Oct 11 '22 16:10

xanatos


Use a ToString pattern:

DateTime.Now.ToString("yyyy-MM-dd-HH-mm") // will produce 2011-10-24-13-10
like image 11
Samich Avatar answered Oct 11 '22 15:10

Samich


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.

  • The "O" format is compliant with ISO 8601, described here
  • The "s" format is described here
like image 3
inwenis Avatar answered Oct 11 '22 17:10

inwenis