繁体   English   中英

字符串到时间格式(无日期)

[英]String to Time format only ( No Date)

我有一个string其值为16:00:00我想将其转换为时间格式hh:mm:ss .. 我不想要日期

TimeSpan.ParseExact(splitLine[6], "hh:mm:ss", null); 抛出错误,system.time无法转换为system.date时间

DateTime.ParseExact(splitLine[6], "hh:mm:ss", CultureInfo.InvariantCulture); 返回日期时间,自动添加今天的日期。

我只想要时间格式。

请帮我。

来自MSDN

仅当format是标准TimeSpan格式字符串(其值为“g”或“G”)时,ParseExact方法才使用formatProvider参数指定的区域性约定。 “c”,“t”和“T”标准格式字符串使用不变文化的格式约定。 自定义格式字符串定义输入字符串的精确格式,并使用文字字符分隔时间间隔的组件。

那么,你可以用它来实现你的目标。

TimeSpan.ParseExact(splitLine[6], "T", CultureInfo.InvariantCulture);

下面的代码呢? 它对我来说很好。

string time = "16:00:00";
TimeSpan.Parse(time);

使用自定义TimeSpan格式字符串,您必须转义冒号(如冒号),例如:

TimeSpan.ParseExact(splitLine[6], "hh':'mm':'ss", null)

要么:

TimeSpan.ParseExact(splitLine[6], @"hh\:mm\:ss", null)

请注意,这是从不同DateTime格式字符串,其中一些分隔符,如冒号: ,有而其他特殊的含义,就像时期. ,没有意义,但不需要逃脱。

暂无
暂无

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

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