Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c# - Culture-specific exact date parsing with and without leading zeroes

I have a string value that represents a date, and I want to parse it into a DateTime. Parsing should succeed, and ONLY succeed, if the format is valid in the specified culture.

Example: Parsing "2/1/2020" should succeed in en-US culture, but fail in de-DE culture. Parsing "1.2.2020" should succeed in de-DE culture, but fail in en-US culture.

My attempts using DateTime.TryParse and DateTime.TryParseExact did not give the results I want.

This returns false, as expected, because the date is in en-US format, and the de-DE culture is used for parsing:

DateTime.TryParseExact("2/1/2020", "d", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)

but so does this because the "d" format requires leading zeroes for month/day values:

DateTime.TryParseExact("1.2.2020", "d", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)

I could use this instead, which returns true:

DateTime.TryParse("1.2.2020", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)

But then so does this, which is bad especially because it returns the wrong date (Jan 2 instead of Feb 1):

DateTime.TryParse("2/1/2020", CultureInfo.GetCultureInfo("de-DE"), DateTimeStyles.None, out date)

How can I do this, without resorting to culture-specific date time format strings for each culture?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...