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.
DateTime.Now.ToString("dd_MM_yyyy")
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
.
Use a ToString pattern:
DateTime.Now.ToString("yyyy-MM-dd-HH-mm") // will produce 2011-10-24-13-10
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:
formatted using "s" are identical.
So if your datetimes represent dirrerent time zones I would recommend using "O" or using DateTime.UtcNow
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With