gpt4 book ai didi

c# - 使用可选的减号解析 TimeSpan

转载 作者:太空狗 更新时间:2023-10-29 21:39:02 26 4
gpt4 key购买 nike

MSDN says :

The styles parameter affects the interpretation of strings parsed using custom format strings. It determines whether input is interpreted as a negative time interval only if a negative sign is present (TimeSpanStyles.None), or whether it is always interpreted as a negative time interval (TimeSpanStyles.AssumeNegative). If TimeSpanStyles.AssumeNegative is not used, format must include a literal negative sign symbol (such as "-") to successfully parse a negative time interval.

我尝试了以下方法:

TimeSpan.ParseExact("-0700", @"\-hhmm", null, TimeSpanStyles.None)

但是它返回 07:00:00。并因“0700”而失败。

如果我尝试:

TimeSpan.ParseExact("-0700", "hhmm", null, TimeSpanStyles.None)

它也失败了。

TimeSpan.ParseExact("0700", new string [] { "hhmm", @"\-hhmm" }, null, TimeSpanStyles.None)

“0700”和“-0700”都不会失败,但始终返回正值 07:00:00。

应该如何使用?

最佳答案

看起来这不受支持。来自custom TimeSpan format strings页:

Custom TimeSpan format specifiers also do not include a sign symbol that enables you to differentiate between negative and positive time intervals. To include a sign symbol, you have to construct a format string by using conditional logic. The Other Characters section includes an example.

虽然这看起来确实很奇怪。恶心。

如我的评论所述,您可以使用我的 Noda Time项目的Duration parsing为了这;对于这种情况有点过分,但如果您在项目中有其他日期/时间工作,它可能会有用。

例如:

var pattern = DurationPattern.CreateWithInvariantCulture("-hhmm");
var timeSpan = pattern.Parse("-0700").Value.ToTimeSpan();

关于c# - 使用可选的减号解析 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27965535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com