Home > Back-end >  Golang time.duration format for C# TimeSpan
Golang time.duration format for C# TimeSpan

Time:01-11

I recently did a bit of Golang and really enjoyed the format for time.duration. For example, "1d2h3s". I could not find a way to use this format with the C# TimeSpan class. Any ideas?

CodePudding user response:

There doesn't seem to exist a formatting implementation the way you found it on Golang but in case you prefer it that way I wrote a custom method to allow you that:

public static class TimeSpanHelper
{
    private static List<(string Abbreviation, TimeSpan InitialTimeSpan)> timeSpanInfos = new List<(string Abbreviation, TimeSpan InitialTimeSpan)>
    {
            ("y", TimeSpan.FromDays(365)), // Year
            ("M", TimeSpan.FromDays(30)), // Month
            ("w", TimeSpan.FromDays(7)), // Week
            ("d", TimeSpan.FromDays(1)), // Day
            ("h", TimeSpan.FromHours(1)), // Hour
            ("m", TimeSpan.FromMinutes(1)), // Minute
            ("s", TimeSpan.FromSeconds(1)), // Second
            ("t", TimeSpan.FromTicks(1)) // Tick
    };

    public static TimeSpan ParseDuration(string format)
    {
        var result = timeSpanInfos
            .Where(timeSpanInfo => format.Contains(timeSpanInfo.Abbreviation))
            .Select(timeSpanInfo => timeSpanInfo.InitialTimeSpan * int.Parse(new Regex(@$"(\d ){timeSpanInfo.Abbreviation}").Match(format).Groups[1].Value))
            .Aggregate((accumulator, timeSpan) => accumulator   timeSpan);
        return result;
    }
}

You can use it in the following way:

var total = TimeSpanHelper.ParseDuration("1d2h3s");

Note that there are built in implementations that allow you to achieve the same result:

The TimeSpan struct has following constructor headers:

public TimeSpan(long ticks)

public TimeSpan(int hours, int minutes, int seconds)

public TimeSpan(int days, int hours, int minutes, int seconds)

public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds)

Therefore we can C#ify your example in the following way:

var total = new TimeSpan(1, 2, 0, 3);

Alternatively we can use some static methods on the TimeSpan struct that allow us to put in a value for a specific time period:

public static TimeSpan FromDays(double value)

public static TimeSpan FromHours(double value)

public static TimeSpan FromMinutes(double value)

public static TimeSpan FromSeconds(double value)

public static TimeSpan FromMilliseconds(double value)

public static TimeSpan FromTicks(long value)

So we could also do:

var total = TimeSpan.FromDays(1)   TimeSpan.FromHours(2)   TimeSpan.FromSeconds(3);
  •  Tags:  
  • Related