Dar*_*yda 0 c# datetime cultureinfo date-parsing
我有一个过滤器字段,允许按可以以不同格式输入的部分或完整日期进行搜索 - 也就是说,无论用户想要以哪种方式输入它,所以 TryParseExact 看起来不是最佳选择。
问题在于下面的代码:
DateTime.TryParse(fromDate.Text, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFromValue)
Run Code Online (Sandbox Code Playgroud)
解析除 yyyy 字符串之外的所有内容。例如,“05/1980”和“1980/05”被识别为 {1/05/1980 12:00:00 AM},但“1980”则失败。
我怀疑解析器无法区分 yyyy 和 ffff 当它得到的只是 4 位序列时,但我仍然需要让它工作。也许有比这更优雅的方法吗
if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Run Code Online (Sandbox Code Playgroud)
或者我完全是以错误的方式做的?
先感谢您!
我认为你不能仅使用 DateTime.Parse 与年份,因为月份和日期不明确。使用具有特定日期格式的 DateTime.ParseExact 或 DateTime.TryParseExact 可以代替。
你的 if 条件对我来说看起来是错误的,你如何结合这两个条件?
if(!DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
Run Code Online (Sandbox Code Playgroud)
本来应该:
if(DateTime.TryParse("1980", CultureInfo.InvariantCulture, DateTimeStyles.None, out date) ||
DateTime.TryParseExact("1980","yyyy",CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
// If the first parse success, use that. Otherwise, try to parse the year only with the parseexact.
// Notice the || and the first condition needs to be positive.
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1182 次 |
最近记录: |