为了账号安全,请及时绑定邮箱和手机立即绑定

C# TimeSpan 的 Golang time.duration 格式

C# TimeSpan 的 Golang time.duration 格式

Go
呼唤远方 2022-10-24 15:19:49
我最近做了一些 Golang 并且非常喜欢time.duration的格式。例如,“ 1d2h3s ”。我找不到在 C# TimeSpan 类中使用这种格式的方法。有任何想法吗?
查看完整描述

1 回答

?
翻阅古今

TA贡献1780条经验 获得超5个赞

似乎不存在您在 Golang 上找到它的方式的格式化实现,但如果您更喜欢这种方式,我编写了一个自定义方法来允许您:


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;

    }

}

您可以通过以下方式使用它:


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

请注意,有一些内置实现可以让您获得相同的结果:


该TimeSpan结构具有以下构造函数头:


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)

因此,我们可以通过以下方式 C#ify 您的示例:


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

或者,我们可以在结构上使用一些静态方法TimeSpan,允许我们输入特定时间段的值:


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)

所以我们也可以这样做:


var total = TimeSpan.FromDays(1) + TimeSpan.FromHours(2) + TimeSpan.FromSeconds(3);


查看完整回答
反对 回复 2022-10-24
  • 1 回答
  • 0 关注
  • 165 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号