tags:

views:

69

answers:

2

With the limitations that a filename provides, what is the simplest way to write a datetime into a filename and then read it back into a datetime in .net?

+2  A: 

how about simply:

DateTime original = DateTime.Today;
string s = original.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact(s, "yyyyMMdd", CultureInfo.InvariantCulture);

(obviously combine with the rest of the file name... add more precision as necessary - hours, minutes, etc)

Marc Gravell
Or use Ticks for more precision
John Sheehan
I didn't know you could do that. Thanks
jimconstable
+2  A: 

EDIT: Unfortunately the original format uses colons, which can't be used in Windows filenames. That's a real shame, as it's otherwise ideal. In that case I'd go for:

 yyyy-MM-dd`T`HH-mm-ss

(with milliseconds if you need them). I don't know if any cultures use anything unusual for any of those fields. That would be quite surprising, but you should probably use CultureInfo.InvariantCulture just to be sure.

I like having the dashes in there though - it makes it easier to parse when you're looking down a list of files.

EDIT: Original answer

I suggest you use the sortable date/time format pattern given by the 's' standard format string, e.g.:

 Console.WriteLine(DateTime.UtcNow.ToString("s"));

which prints something like:

 2009-04-08T06:45:43

This is easy for humans to parse, easy for computers to parse, culture-independent, and sorts appropriately.

Jon Skeet
Can't use the : character in a filename though...
sipwiz
that was my problem
jimconstable
Ah, true. Editing...
Jon Skeet