+/- 登录 TimeSpan 的 ParseExact()?

+/- sign in TimeSpan's ParseExact()?

我需要解析指定环境时区的字符串。它看起来像 +0100-0530,指定与 UTC 时区的偏移量。

在这些字符串中,plus/minus 符号总是。我想用 TimeSpan.ParseExact() 方法解析它,我很确定有办法。 Parse() 方法知道如何处理减号,但 the ParseExact() method's documentation 没有提及任何有关符号的内容。

到目前为止,我使用的格式是 hhmm,但这需要以处理 +/- 符号的内容作为前缀。谁能给我指明正确的方向?

这应该适用于时区偏移:

var dt = DateTime.ParseExact("14-oct-2015 08:22:00 +01:00","dd-MMM-yy HH:mm:ss zzz", culture);

但这仅适用于 DateTime,不适用于 TimeSpan,因为 TimeSpan 字符串不支持时区信息。

看起来不支持。来自 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.

但看起来像 NodaTime support this. In Patterns for Duration values 页面,它有 +- 作为字符部分。

using NodaTime.Text;

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            DurationPattern pattern = DurationPattern.CreateWithInvariantCulture("+hhmm");
            TimeSpan timeSpan = pattern.Parse("+0100").Value.ToTimeSpan();
        }
    }
}

这里是demonstration.

您可以检查它是否以 - 开头,然后应用适当的格式字符串:

string[] timespans = { "-0530", "+0100" };
foreach (string timespan in timespans)
{
    bool isNegative = timespan.StartsWith("-");
    string format = isNegative ? "\-hhmm" : "\+hhmm";
    TimeSpanStyles tss = isNegative ? TimeSpanStyles.AssumeNegative : TimeSpanStyles.None;
    TimeSpan ts;
    if (TimeSpan.TryParseExact(timespan, format, null, tss, out ts))
    {
        Console.WriteLine("{0} successfully parsed to: {1}", timespan, ts);
    }
    else
    {
        Console.WriteLine("Could not be parsed: {0}", timespan);
    }
}

请注意,我在 TryParseExact 中使用 TimeSpanStyles.AssumeNegative,否则时间跨度将始终为正,即使它们前面带有负号。