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);
- 1 回答
- 0 关注
- 165 浏览
添加回答
举报
