NOTE - Yes, the question from 2011 that my question is suggested as a dupe of, this one here, has answers I could use, but Zohar's answer below is by far the best of all of them, and possibly takes into consideration advances in C# that did not exist 7 years ago. Thus the question is indeed a dupe, but the best answer is found HERE, not THERE.
I'm reading the EXIF information in digital photographs taken with a camera, and photographs scanned by my scanner, and am finding that while the Canon scanner formats the date with "/", the Fujifilm camera formats them with ":". I need to parse these strings to DateTime, and would like a nifty short way of doing it. I don't know if other makers provide EXIF data with yet different date formats, such as hyphens ("-"), periods (".") or some other delimiter, and how I am supposed to allow for all of them? I know one way to do it (try-catch blocks looking for FormatException), but is there a better way?
By the way, the EXIF standard specifies yyyy:mm:dd, with the colon (:) for delimiter, but as mentioned, my Canon scanner (Canoscan 9000F Mk II) uses the slant (/). Presumably other makers could use a different delimiter.
The camera is providing: "2008:10:06 16:00:07"
For which I can do:
DateTime dt = DateTime.ParseExact(str, "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
Or try to catch several variants as follows:
try
{
dt = DateTime.ParseExact(str, "yyyy:MM:dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
catch (FormatException)
{
try
{
dt = DateTime.ParseExact(str, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
catch (FormatException)
{
try
{
dt = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
}
catch (FormatException ex)
{
throw ex;
}
}
}
Don't get me started on all the rest of the formats that could occur!