You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用DateTime.ParseExact转换日历选择的日期字符串时出现类型错误的问题求助

问题分析与解决

我在开发一个日期范围查询功能时碰到了麻烦:这个功能需要从两个日历控件选择日期,把日期显示到文本框后,再从独立JSON文件里获取chosenDate_start到chosenDate_end区间内每天的CountyInfectionNumber和Incidence数据。需要说明的是,JSON文件的格式是固定的,虽然看起来有些不规范。

报错核心点

代码里这两行一直报错,提示chosenDate_不能是字符串,但我明明用了ParseExact来做字符串转DateTime的操作:

DateTime loadedDate_start = DateTime.ParseExact(chosenDate_start, "d", null);
DateTime loadedDate_end = DateTime.ParseExact(chosenDate_end, "d", null);

问题根源

你往前看代码里的日期生成逻辑:

ZiAleasaatunci.Text = Calendar_de_Ales_Inc.SelectionRange.Start.ToString("yyyy-MM-dd");
ZiSfarsitAleasaAtunci.Text = Calendar_Ales_Sf.SelectionRange.End.ToString("yyyy-MM-dd");
chosenDate_start = ZiAleasaatunci.Text;
chosenDate_end = ZiSfarsitAleasaAtunci.Text;

这里是把日期转成了yyyy-MM-dd格式的字符串,但后面ParseExact用的格式参数是"d"(这是系统默认的短日期格式,比如MM/dd/yyyy或者dd/MM/yyyy,取决于系统区域设置),字符串格式和解析格式不匹配,导致解析失败抛出错误。

解决方案

把ParseExact的格式参数改成和前面日期生成一致的"yyyy-MM-dd"就可以解决问题,另外建议加上CultureInfo.InvariantCulture参数,避免系统区域设置影响解析结果:

修正后的完整代码片段:

{ 
using (var webClient = new System.Net.WebClient()) { 
    json = webClient.DownloadString("https://datelazi.ro/latestData.json"); 
} 
var semiParsedData = JObject.Parse(json); 
string chosenDate_start; 
string chosenDate_end; 
string chosenCounty; 
ZiAleasaatunci.Text = Calendar_de_Ales_Inc.SelectionRange.Start.ToString("yyyy-MM-dd"); 
ZiSfarsitAleasaAtunci.Text = Calendar_Ales_Sf.SelectionRange.End.ToString("yyyy-MM-dd"); 
chosenDate_start = ZiAleasaatunci.Text; 
chosenDate_end = ZiSfarsitAleasaAtunci.Text; 
chosenCounty = JudeteAtunci.Text; 
//var countySpecificInfections = semiParsedData.SelectToken($"historicalData.{chosenDate_start}.countyInfectionsNumbers.{chosenCounty}"); 
//var countySpecificIncidence = semiParsedData.SelectToken($"historicalData.{chosenDate_start}.incidence.{chosenCounty}"); 
//NumarCazuriAtunci.Text = countySpecificInfections.Value<int>().ToString(); 
//IncidentaAtunci.Text = countySpecificIncidence.Value<double>().ToString(); 

// 修正:使用与字符串生成一致的格式,并指定不变文化避免区域影响
DateTime loadedDate_start = DateTime.ParseExact(chosenDate_start, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 
DateTime loadedDate_end = DateTime.ParseExact(chosenDate_end, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture); 

List<DateTime> allDates = new List<DateTime>(); 
DateTime Zi_Aleasa = loadedDate_start ; 
DateTime Zi_Precedenta = Zi_Aleasa.AddDays(-1); 
Console.WriteLine(Zi_Precedenta); 
for (DateTime date = loadedDate_start; date <= loadedDate_end; date = date.AddDays(1)) 
    allDates.Add(date); 
}

致谢

感谢@insane_developer在评论区帮忙解决了这个问题!


内容的提问来源于stack exchange,提问作者Nistor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:47:31