TimeSpan synchronization from string, including format

I am sure it should be simple, but I can’t figure out how to write it correctly on Google ...

I have a config that has a field:

TimeToPoll="1d"

Now I want to do something like :

TimeSpan.Parse(TimeToPoll);

Return time interval of one day.

In c #

EDIT: I'm looking for a method that allows you to parse "1d" as well as "1s" or "1y" etc. Is it possible?

Value:

     "1d" parses to {1.00:00:00}
     "1h" parses to {0.01:00:00}
     "1m" parses to {0.00:01:00}
     "1s" parses to {0.00:00:01}
+5
source share
3 answers

d not needed and is the reason why your parsing is not performed.

var oneDay = TimeSpan.Parse("1");

Update:

There is no built-in support for what you want to do. You will need to write your own parser.

0
source

This is my permission:

    public static TimeSpan ConvertToTimeSpan(this string timeSpan)
    {
        var l = timeSpan.Length - 1;
        var value = timeSpan.Substring(0, l);
        var type = timeSpan.Substring(l, 1);

        switch (type)
        {
            case "d": return TimeSpan.FromDays(double.Parse(value));
            case "h": return TimeSpan.FromHours(double.Parse(value));
            case "m": return TimeSpan.FromMinutes(double.Parse(value));
            case "s": return TimeSpan.FromSeconds(double.Parse(value));
            case "f": return TimeSpan.FromMilliseconds(double.Parse(value));
            case "z": return TimeSpan.FromTicks(long.Parse(value));
            default: return TimeSpan.FromDays(double.Parse(value));
        }
    }
+4
source

, TimeSpan.Parse. .

EDIT: .

0
source

All Articles