英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论