C# 声明变量只是时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1706801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declare variable for just time
提问by Lasse Edsvik
I need to create a variable that contains time in the format hh:mm, how shall I do that?
我需要创建一个包含 hh:mm 格式的时间的变量,我该怎么做?
DateTime currentTime = "00:00";
doesn't seem to do the trick. I need to add hours/minutes in a loop to that variable and keep the format "hh:mm". How is that done?
似乎没有办法。我需要在循环中向该变量添加小时/分钟,并保持格式“hh:mm”。这是怎么做的?
/M
/M
采纳答案by F.P
Probably use TimeSpan
for that?
大概TimeSpan
是用来干嘛的?
回答by Espo
You could use a normal datetime-variable with todays date, starting at midnight.
您可以使用正常的日期时间变量与今天的日期,从午夜开始。
回答by erikkallen
A simple integer? hours = number / 60; minutes = number % 60
一个简单的整数? hours = number / 60; minutes = number % 60
回答by Jon Skeet
You should distinguish between the quantity you're trying to keep track of, and the eventual string formatting. They're different things.
您应该区分您要跟踪的数量和最终的字符串格式。它们是不同的东西。
Are you trying to maintain a time of day (in which case using DateTime
and ignoring the date part is probably best) or a duration of time (in which case TimeSpan
is most appropriate)? Either way, pick your data type, use it in your loop, and then deal with formatting as and when you need to.
您是要维护一天中的时间(在这种情况下使用DateTime
和忽略日期部分可能是最好的)还是持续时间(在这种情况下TimeSpan
最合适)?无论哪种方式,选择您的数据类型,在循环中使用它,然后根据需要处理格式。
(Just as a heads-up, I'm part of a new project called Noda Timewhich keeps all of these as different types; it's a port of the popular Joda Timeproject for Java. We're a very long way from releasing anything, but in a year's time I hope it would be the best answer for this question :)
(作为提醒,我是一个名为Noda Time的新项目的一部分,该项目将所有这些保持为不同的类型;它是Java流行的Joda Time项目的一个端口。我们离发布任何东西还有很长的路要走,但在一年的时间里,我希望这将是这个问题的最佳答案:)
回答by Lee Conroy
Timespan is your best bet, or use DateTime.toString("hh:mm")
时间跨度是你最好的选择,或者使用 DateTime.toString("hh:mm")
回答by PaulB
You could use the following and ignore the date part
您可以使用以下内容并忽略日期部分
DateTime current;
DateTime.TryParse("13:00", out current);
To get just the time out use
为了得到超时使用
current.ToString("hh:mm");