I need to reliably determine if a user inputted string is a date or a number.
Consider the string 1.1
. This string successfully parses to a double using
double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out var result)
This string also successfully parses to DateTime using
DateTime.TryParse(s, out var dResult)
We need this string to be interpreted as a double in English.
More complexity comes when you consider other cultures.
In German for example the NumberGroupSeperator and the DateSeperator are both dots, rather than a comma and slash, as in English. So in German, the string 1.1
should actually parse to a DateTime (ie: January 1 of the current year). The only way to know this programatically is to validate the NumberGroupSeperator and the NumberGroupSizes (because the string 1.1
in German is equivalent to 1,1
in English, which we know should not be parsed to a double or integer because the NumberGroupSeperator (comma) is in the wrong place).
From reading documentation (and this super passive aggressive GitHub issue conversation) there is no way for .NET to actually validate the NumberGroupSeperator and NumberGroupSizes when parsing.
Has anyone encountered this issue before and how did you solve it?
I wrote some code to manually validate the NumberGroupSeperator and NumberGroupSizes, but it seems like there should be a better way. I can share this code if anyone is interested.
EDIT
For those of you asking for more information about the business problem. I'm working on an open source project that allows users to edit Excel spreadsheets via a c# API. Consider someone entering the string "1.1" into cell A1 and the string "1" into cell B1 and then uses this open source library to try to calculate the formula =A1+B1 in another cell. This project needs to parity Microsoft Excel exactly. So if we're in a language/culture where "1.1" is interpreted as a date, then the result of this addition should be the OADate of Jan 1, 2018 plus one (ie: 43101 + 1 = 43102). But if we're in a language where "1.1" is the number 1.1 then the result of this calculation should be 1.1 + 1 = 2.1.
And yes, we do know the user's language/culture when doing this calculation, but the solution needs to work in all cultures.