解析确切的自定义时间格式? [英] Parse exact custom time format?

查看:55
本文介绍了解析确切的自定义时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法正确获取 TimeSpan.ParseExact()的自定义格式:

I can't seem to get the custom format right for my TimeSpan.ParseExact():

预期的时间样本:

1:23:45.6
23:45.6
23:45
1:23:45

我正在使用的字符串格式:

The string format I'm using:

string withTenthFormat = @"[%h\:]mm\:ss[\.%f]";

尝试选择小时和几分之一秒.但是,使用这种格式和 CultureInfo.InvariantCulture 确实会导致 FormatException .我想念什么?

Trying to have hours and fractions of seconds optionally. However using this format and an CultureInfo.InvariantCulture does lead to a FormatException. What am I missing?

推荐答案

我不知道是否可以在自定义格式字符串中指定可选部分.我建议您使用多个格式字符串,并使用采用格式数组的 TimeSpan.ParseExact 的重载.

I'm not aware of the ability to specify optional parts like that in a custom format string. I suggest you use multiple format strings, and use the overload of TimeSpan.ParseExact that takes an array of formats.

string[] formats = { @"h\:mm\:ss\.FFF", @"mm\:ss\.FFF",
                     @"h\:mm\:ss", @"mm\:ss"};
string[] values = { "1:23:45.6", "23:45.6", "23:45", "1:23:45" };

foreach (string value in values)
{
    var parsed = TimeSpan.ParseExact(value, formats,
                                     CultureInfo.InvariantCulture);
    Console.WriteLine(parsed);
}

(我将 FFF 用作毫秒说明符,以便您也可以表达"1:23:45.67".如果您只想 ever 想要数百毫秒,, F f 都可以.)

(I'm using FFF as the milliseconds specifier to allow you to express "1:23:45.67" as well. If you only ever want hundreds of milliseconds, F or f would be fine.)

这篇关于解析确切的自定义时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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