默认午夜时间跨度

huangapple go评论54阅读模式
英文:

Default timespan for midnight

问题

我试图计算从一天中的任何时间到午夜的时间跨度。我的尝试如下,但我不想让它短暂一秒钟。是否有默认值或更好的方法?

TimeSpan sinceMidnight = TimeSpan.Parse("23:59:59") - TimeSpan.Parse("21:48:42");

Console.WriteLine(sinceMidnight);
英文:

I'm trying to calculate the timespan from any time of the day till midnight. My attempt is below, but I don't want to make it short for one second. Is there any default value or a better way?

TimeSpan sinceMidnight = TimeSpan.Parse("23:59:59") - TimeSpan.Parse("21:48:42");

Console.WriteLine(sinceMidnight);

答案1

得分: 1

为什么你要使用字符串解析呢?你也可以从数字生成时间跨度:

TimeSpan sinceMidnight = TimeSpan.FromHours(24) - new TimeSpan(21, 48, 42);

字符串解析有两个缺点:它很慢(但很可能你不会注意到,因为性能差异可以忽略不计)。如果你的字符串中有一些拼写错误,并且格式不正确,编译时你不会意识到它。这可能导致异常。

英文:

Why do you use string parsing at all? You can also generate the timespans from numbers:

TimeSpan sinceMidnight = TimeSpan.FromHours(24) - new TimeSpan(21, 48, 42);

String parsing has two disadvantages: It is slow (but it is quite probable you won't notice it because the difference in performance can be neglected). And if you have some typos in your string and it will have the wrong format you won't realize during compile time. This might result in exceptions.

huangapple
  • 本文由 发表于 2023年6月22日 14:49:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529240.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定