登录
首页 >  Golang >  Go问答

如何在Golang中将时间间隔转换为C# TimeSpan格式

来源:stackoverflow

时间:2024-02-23 19:03:27 466浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《如何在Golang中将时间间隔转换为C# TimeSpan格式》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

我最近做了一些 Golang,并且非常喜欢 time.duration 的格式。例如,“1d2h3s”。我找不到在 C# TimeSpan 类中使用此格式的方法。有什么想法吗?


正确答案


似乎没有像您在 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# 化:

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);

今天关于《如何在Golang中将时间间隔转换为C# TimeSpan格式》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>