C#字符串转DateTime报FormatException 对比当前时间与日落时间异常
C# 时间比对时DateTime解析报错问题解决
问题背景
需要在C#中比对当前时间与日落时间,判断当前是否处于日落之前,用到的两个时间字段均从第三方API获取:
- 当前时间字段
Weather.location.localtime示例值:2021-12-02 16:19 - 日落时间字段
SunriseSunset.results.sunset示例值:05:55:50 PM
最初使用的代码如下:
var currentTime = DateTime.ParseExact(Weather.location.localtime, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture).TimeOfDay; var sunsetTime = DateTime.ParseExact(SunriseSunset.results.sunset, "hh:mm:ss tt", CultureInfo.InvariantCulture).TimeOfDay; bool sunStillUp = currentTime < sunsetTime;
运行时抛出异常:System.FormatException: String was not recognized as a valid DateTime,已确认是日期字符串与格式串不匹配导致,但无法定位具体问题点。
问题根因与修复方案
1. 当前时间字段解析错误
你使用的格式串yyyy-MM-dd HH:mm要求月份、日期、小时、分钟必须是双位数,而从API返回的字段特征来看,当个位数的月份、日期、小时、分钟返回时没有前导零,和格式串不匹配导致解析失败。
修改格式串为兼容单/双位的写法即可:
// 单个M、d、H、m可自动适配单/双位的对应时间字段 var currentTime = DateTime.ParseExact(Weather.location.localtime, "yyyy-M-d H:m", CultureInfo.InvariantCulture).TimeOfDay;
2. 日落时间字段解析错误
12小时制的时间字符串容易出现首尾空格、个位数小时无前导零的问题,ParseExact的严格匹配规则会因此报错,优化写法如下:
// 先移除首尾空格,同时传入多个兼容的格式串提升容错率 string sunsetStr = SunriseSunset.results.sunset.Trim(); var sunsetTime = DateTime.ParseExact(sunsetStr, new string[] {"hh:mm:ss tt", "h:mm:ss tt"}, CultureInfo.InvariantCulture, DateTimeStyles.None).TimeOfDay;
3. 更稳定的实现方案
如果不能保证API返回格式完全稳定,建议使用TryParseExact替代ParseExact,避免解析失败直接抛出异常:
TimeSpan currentTime, sunsetTime; bool parseCurrentSuccess = TimeSpan.TryParseExact(Weather.location.localtime.Split(' ')[1], "H:m", CultureInfo.InvariantCulture, out currentTime); bool parseSunsetSuccess = TimeSpan.TryParseExact(SunriseSunset.results.sunset.Trim(), new string[] {"hh:mm:ss tt", "h:mm:ss tt"}, CultureInfo.InvariantCulture, DateTimeStyles.None, out sunsetTime); if (parseCurrentSuccess && parseSunsetSuccess) { bool sunStillUp = currentTime < sunsetTime; // 后续业务逻辑 } else { // 解析失败的兜底逻辑 }
内容的提问来源于stack exchange,提问作者cesq
相关产品推荐
相关产品推荐

