Is there a standard DateTime string representation that is valid as a Windows file name and can be parsed using DateTime.Parse?
As part of a simple backup process, I would like to save files with the name indicating the date and time of the backup. Right now I am using yyyyMMddTHHmmss, i.e. "20100601T115720". I would like to be able to parse those dates back to allow clean up of files older than a certain date. (The backup date time is not necessary the same as the file created date.) This ultimately runs in Powershell, using a line something like the following:
Get-ChildItem $backupDirectory -filter *.bak | 开发者_如何学编程where { [System.DateTime]::ParseExact([System.IO.Path]::GetFileNameWithoutExtension($_), "yyyyMMddTHHmmss", [System.Globalization.CultureInfo]::InvariantCulture) -lt $oldestDate }
Note that I am currently using the DateTime.ParseExact
method. This works great, and so I guess my question is more academic, but I'm wondering if there a "standard" Windows file name format that:
- Includes both date and time information AND
- Can be parsed using the standard DateTime.Parse
This is no "standard" filename format.
I usually use yyyy-MM-dd, HH-mm-ss
, which is a lot more readable than a blob of numbers.
There isn't a standard filename format that I've found, either, but this trick tends to work well for making PowerShell output a localized readable date/time (i.e. February 2nd, 2010 8:15:14 AM):
(Get-Date | Out-String).Trim().Replace(":", "-")
Piping Get-Date to Out-String uses the default formatter (in this case, the time in the current locale) to make the date a readable string. Trim() removes the extra newlines from both ends. Since the only illegal character in the time strings of of the locales I am aware of is ':', I simply replace ':' with '-'
It's most definately a notch slower than using .NET's string formatting. If you want to use the same trick without using cmdlets, you can write it this way:
$date = [DateTime]::Now
($date.ToLongDateString() + " " + $date.ToLongTimeString()).Replace(":",'-')
Hope this helps
精彩评论