Parsing string input C# -
let's have string bound console input , must contain date data in of following formats:
"dd/mm/yyyy" "dd.mm.yyyy" "dd,mm,yyyy"
what safest way parse string datetime
object? should use regex
approach or iterate through string.format()
method possible upper mentioned input formats till succeeds in parsing?
it's not enough use datetime.parseexact or datetime.tryparseexact. /
special formatting character, date separator character. in format string replaced whatever date separator application's current culture. can't escaped because not special character \
. cause problems if system's culture uses .
(russia , other countries).
to specify different date separator need create cultureinfo object separator want. following function accepts list of separators , tries parse dates using each separator until 1 of them succeeds:
public static bool tryparsedate(string input, string[] separators, out datetime date) { var ci = (cultureinfo) cultureinfo.invariantculture.clone(); foreach (var separator in separators) { ci.datetimeformat.dateseparator = separator; datetime result; if (datetime.tryparseexact(input, "dd/mm/yyyy", ci, datetimestyles.none, out date)) return true; } date=new datetime(); return false; }
there's no need define multiple formats because dd/mm/yyyy
matches cases.
this allows write code following snippet:
var separators = new []{"/",".",",","-"}; datetime result; var success1 = tryparsedate("12.05.2015", separators, out result); var success2 = tryparsedate("12/05/2015", separators, out result); var success3 = tryparsedate("12,05,2015", separators, out result); var success4 = tryparsedate("12-05-2015", separators, out result);
i added -
because see it's common separator in germany. can make function more generic passing format parameter.
tryparseexact
accepts multiple format parameters. if weren't /
separator, write single call formats:
var formats=new []{"dd.mm.yyyy","dd,mm,yyyy","dd-mm-yyyy"}; datetime result; var success=datetime.tryparseexact(input, formats, cultureinfo.invariantculture, datetimestyles.none, out date)