TimeSpan.ParseExact 给出错误 [英] TimeSpan.ParseExact giving error

查看:27
本文介绍了TimeSpan.ParseExact 给出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式创建了一个 TimeSpan

I created a TimeSpan this way

TimeSpan ts = new Timespan();

// Do some addition and subtraction on it

然后我将它保存到一个文件中

Then I am saving it to a file using this

string.Format("{0}:{1}:{2}:{3}", ts.Hours, ts.Minutes, ts.Seconds, ts.MilliSeconds);

从它返回的各种值是这样的

Various values returned from it are like this

0:0:4:410
0:0:1:425
0:0:1:802
0:0:1:509
0:0:1:674
0:0:1:628
0:0:2:76

如何将其转换回 TimeSpan.

How to convert it back to TimeSpan.

我正在使用

TimeSpan.ParseExact("0:0:4:410", "h:m:s:fff", null); 

但它给了我错误输入字符串的格式不正确.

我哪里错了?

推荐答案

我相信您基本上需要解析冒号.我还建议使用不变文化而不是当前的线程文化:

I believe you need to parse the colons, basically. I would also suggest using the invariant culture instead of the current thread culture:

var ts = TimeSpan.ParseExact("0:0:4:410", @"h\:m\:s\:fff",
                             CultureInfo.InvariantCulture);

来自文档:

自定义 TimeSpan 格式说明符不包括占位符分隔符,例如将天与小时、小时与分钟或秒与小数秒分开的符号.相反,这些符号必须作为字符串文字包含在自定义格式字符串中.例如,dd.hh:mm"将句点 (.) 定义为天和小时之间的分隔符,将冒号 (:) 定义为小时和分钟之间的分隔符.

The custom TimeSpan format specifiers do not include placeholder separator symbols, such as the symbols that separate days from hours, hours from minutes, or seconds from fractional seconds. Instead, these symbols must be included in the custom format string as string literals. For example, "dd.hh:mm" defines a period (.) as the separator between days and hours, and a colon (:) as the separator between hours and minutes.

建议改用 h:mm:ss.fff 的格式 - 我相信这会比您当前的格式更清晰.请注意,您可以直接使用格式而不是当前的格式设置方法:

I would also suggest using a format of h:mm:ss.fff instead - I believe this would be clearer than your current format. Note that you can use the format directly instead of your currently formatting approach:

const string TimeSpanFormat = @"h\:mm\:ss\.fff";

string text = ts.ToString(TimeSpanFormat, CultureInfo.InvariantCulture);
...
TimeSpan parsed = TimeSpan.ParseExact(text, TimeSpanFormat,
                                      CultureInfo.InvariantCulture);

这篇关于TimeSpan.ParseExact 给出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆