TimeSpan.TryParseExact不工作 [英] TimeSpan.TryParseExact not working

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

问题描述

我尝试从一个字符串时间跨度,但TryParseExact是返回false(失败)。



我不明白我在做什么错, 你能帮我吗?我试过2个版本我行的代码,都不起作用。

  TimeSpan.TryParseExact(04:00 :01,HH:MM:SS,CultureInfo.CurrentCulture,出ATIME)

  TimeSpan.TryParseExact(4点00分01秒,HH:MM:SS,空,出ATIME)

编辑:
这里两种反应是正确的,我有错误的格式为我的自定义时间跨度格式 - 我所犯的错误是假设的日期时间的自定义格式会为时间跨度的工作,但他们没有。


解决方案

问题只是在格式字符串的时间跨度,您指定HH:MM:SS。该说明 HH (大写)是无效的时间跨度。您应该使用 HH 。 。格式化字符串确实是区分大小写



的冒号()也需要进行转义,所以使用hh\\:mm\\:SS @hh\:mm\:SSHH:毫米:SS。所有三种形式都会有同样的效果。



您可以查看时间跨度的here 。和时间跨度的标准格式字符串是这里



HH 有效期为DateTime和的DateTimeOffset它代表24小时制和较低的情况下,HH代表12小时制,对于时间跨度 - 小时分量总是基于24小时。你可能会认为 HH 格式将是一个选择,对于均匀性,但都能跟得上 - 这是 HH

I'm trying to retrieve a timespan from a string, but TryParseExact is returning false (fail).

I can't see what I'm doing wrong, can you help? I've tried 2 versions of my line in the code, both do not work.

TimeSpan.TryParseExact("04:00:01","HH:mm:ss",CultureInfo.CurrentCulture, out aTime)

and

TimeSpan.TryParseExact("04:00:01","HH:mm:ss", null, out aTime)

EDIT: both responses here are correct, I have the wrong format for my custom timespan format - the mistake I made is to assume that the custom formats for DateTime would work for TimeSpans, but they do not.

解决方案

The problem is simply in the format string for the TimeSpan, you have specified "HH:mm:ss". The specifier HH (upper case) is not valid for timespan. You should use hh. Format strings are indeed case sensitive.

The colon character (:) also needs to be escaped, so use "hh\\:mm\\:ss", @"hh\:mm\:ss" or "hh':'mm':'ss". All three forms will have the same effect.

You can review a list of valid custom format strings for TimeSpan here. and the standard format strings for TimeSpan are here.

While HH is valid for DateTime and DateTimeOffset where it represents the 24 hour clock and lower case hh represents a 12 hour clock, For TimeSpan - the hours component is always based on 24 hours. You would think that the HH format would be the one chosen, for uniformity, but nope - it's hh.

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

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