繁体   English   中英

输入字符串格式不正确无法解析为DateTime

[英]Input string not in correct format to parse into DateTime

我在12小时时钟机上将DataTime转换为时间时遇到问题。 以下代码在24小时时钟机上正常工作。

(new DisplayReminder(_name, _displayText, _snoozTime, TimeSpan.Parse(_startTime.ToShortTimeString(), CultureInfo.InvariantCulture))).Show();

TimeSpan.Parse(_startTime.ToShortTimeString()抛出异常输入字符串格式不正确,这里我试图从DateTime值获取时间部分_startDate对此问题的任何建议或解决方案。

目前还不清楚你要做什么,但只是获取时间不应该涉及字符串转换:

TimeSpan time = _stateTime.TimeOfDay;

我强烈建议你避免字符串转换,除非它们本身就是你想要达到的目标的一部分。

就个人而言,我不喜欢使用TimeSpan作为时间,但那是你的BCL。 您可能还想查看我的Noda Time库,它可以更清晰地分离各种日期/时间概念。

试试这个:

TimeSpan.ParseExact(
         _startTime.ToString("hh:mm:ss"), "hh:mm:ss",
                          System.Globalization.CultureInfo.InvariantCulture);

它会将你的日期格式化为TimeSpan.ParseExact接受的相同格式,因此它将在任何机器上运行(我假设_startTime是DateTime

尝试

startTime.TimeOfDay.ToString()

我很确定它在24小时工作正常但在12H系统中崩溃,因为“PM”“AM”部分! 摆脱它你将是安全的11:54:33 PM和23:54:33在处理方面是非常不同的

编辑它可能不是最好的解决方案,但如果你剪切字符串的最后一个索引它是有效的:

    int index = _StartTime.IndexOf("M");
    if (index >= 0) 
{
_StartTime = _StartTime.Substring(0, index-1);
switch (_StartTime.IndexOf("P"))
case : -1
 _StartTime = _StartTime.Substring(0,_StartTime.Length);
 break;

default:
 string hours = _startTime.Substring(_StartTime.Length-8,2);
 int H = Convert.ToInt32(hours);
 H += 12;
 string result = _StartTime.Substring(0, _StartTime.Length-8)+ Convert.ToString(H)+_startTime.Substring(_StartTime.Length-6);

_StartTime = result;
break;
}

这将抛出AM / PM,你可以使用相同的先前代码在这次SECOND EDIT之后这是最可怕的解决方案,但它有效;)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM