I have a system that outputs dates in the format “1{yy}{MM}{dd}” and I am trying to find a good way to parse it back into a real date.
At the moment I am using this:
var value = "1110825";
var z = Enumerable.Range(1,3).Select(i => int.Parse(value.Substring(i, 2))).ToList();
var d = new DateTime(2000 + z[0], z[1], z[2]);
but I’m sure there’s a cleaner/more efficient way to do it?
I’ve tried DT.ParseExact, but can’t find a suitable format string to use.
This works for me:
(You may want to use
TryParseExactof course, if you need to cope with invalid data in any way other than with an exception.)A slight variation of this is the format pattern of “‘1’yyMMdd” – note the apostrophes round the 1. That quotes the 1 to force it to be treated as a “literal” in the pattern. It’s not important in this case, but if you actually had values such as “y110825” then you’d want to quote the
yto make sure it wasn’t treated as part of a year specifier.