我已经知道了如何将输入字符串解析为日期时间对象。
但是,如果我输入字符串并运行启动计时器的方法,然后停止它,我将无法在不获得格式异常的情况下重新编辑字符串输入。
在测试中,我输入:"00 : 00 : 10 : 000"
,然后启动我的计时器和秒表,但是当我调用stop时,尝试为字符串输入一个新的值,例如"00 : 00 : 22 : 000"
,它给了我以下例外:
An exception of type 'System.FormatException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: String was not recognized as a valid DateTime.
以下是将字符串解析到日期时间的方式:
//Assign text box string value to a date time variable.
DateTime workDt = DateTime.ParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
DateTime restDt = DateTime.ParseExact(rstString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);
在代码中是否有处理这种类型的输入异常的方法,或者在解析字符串时可能遗漏了一个额外的步骤?
发布于 2014-10-09 10:11:27
{这是评论,不是答复,但我需要正确地格式化它。}
一定还有一些其他的信息导致了你没有提供的问题。这对我来说很管用:
string s= "00 : 00 : 10 : 000";
DateTime workDt = DateTime.ParseExact(s, "HH : mm : ss : fff", CultureInfo.InvariantCulture);
s= "00 : 00 : 22 : 000";
DateTime restDt = DateTime.ParseExact(s, "HH : mm : ss : fff", CultureInfo.InvariantCulture);
但是,由于您只处理时间数据,所以最好使用TimeSpan
:
string s= "00 : 00 : 10 : 000";
TimeSpan workTm = TimeSpan.ParseExact(s, @"hh\ \:\ mm\ \:\ ss\ \:\ fff", CultureInfo.InvariantCulture);
s= "00 : 00 : 22 : 000";
TimeSpan restTm = TimeSpan.ParseExact(s, @"hh\ \:\ mm\ \:\ ss\ \:\ fff", CultureInfo.InvariantCulture);
注意,在使用TimeSpan.Parse
时,需要将冒号和空格转义。
发布于 2014-10-09 10:01:13
尝试转换类:
myDateAsString="3/29/2014";
try
{
Convert.ToDate(myDateAsString)
}
catch(Format exception)
{
//do something
}
这是另一种方法,我同意这一点,但我认为这更容易,我希望它能有所帮助:)
发布于 2014-10-09 10:05:07
如果您知道某些事情可能出错,我建议您使用TryParseExact
方法。
我还建议在使用时间间隔时使用TimeSpan而不是DateTime。无论如何,这种方法也存在于DateTime.
TimeSpan ts;
if (TimeSpan.TryParseExact(wrkString.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture, out ts))
{
//ts formatted successfully
}
else
{
//failure
}
https://stackoverflow.com/questions/26284987
复制