使用可选的减号解析 TimeSpan

Parsing TimeSpan with optional minus sign

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)

然而它 returns 07:00:00。并因“0700”而失败。

如果我尝试:

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

也失败了

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

“0700”和“-0700”都不会失败,但总是 return 正数 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 project's Duration parsing;对于这种情况有点过分,但如果您在项目中有其他 date/time 工作,它可能会有用。

例如:

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

看起来您确实需要检查自己是否以前导 -

开头
// tsPos = 07:00:00
string pos = "0700";
TimeSpan tsPos = TimeSpan.ParseExact(pos, new string [] { "hhmm", @"\-hhmm" }, null,
    pos[0] == '-' ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None);

// tsNeg = -07:00:00            
string neg = "-0700";
TimeSpan tsNeg = TimeSpan.ParseExact(neg, new string [] { "hhmm", @"\-hhmm" }, null,
    neg[0] == '-' ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None);