C# 使用前导零获取日期时间小时和分钟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10341886/
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
Get Date Time Hours and Minutes with leading Zero
提问by Encryption
I'm trying to figure out the simplest code to add leading zeros on to the hours and minutes from the DateTime.Now function. I need to combine only the hours and minutes, and I don't need the rest of the date.
我试图找出最简单的代码,将前导零添加到 DateTime.Now 函数的小时和分钟上。我只需要结合小时和分钟,我不需要日期的其余部分。
Whats the best way to do this?
什么是最好的方法来做到这一点?
My code looks like this:
我的代码如下所示:
DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
However I get data such as 16:4 for 4:04PM and I need it to look like 16:04. I'm familiar with the msdn articles on datetime formatting but I didn't see anything that addresses this specifically.
但是,我在下午 4:04 获得了诸如 16:4 之类的数据,我需要它看起来像 16:04。我熟悉有关日期时间格式的 msdn 文章,但我没有看到任何专门解决此问题的内容。
Is it possible combining `DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
是否可以结合`DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
If not how would I pull only the HH:MM out of DateTime.Now easily?
如果不是,我将如何轻松地从 DateTime.Now 中仅提取 HH:MM?
Looking for least lines of code possible because this is something that I will be utilizing often. Thanks
寻找尽可能少的代码行,因为这是我将经常使用的东西。谢谢
采纳答案by Dismissile
DateTime.Now.ToString("hh:mm") // for non military time
DateTime.Now.ToString("HH:mm") // for military time (24 hour clock)
Using hhvs hwill do a leading 0. Same with mmfor minutes. If you want seconds, you can use ss.
使用hhvsh将做一个前导 0。与mm分钟相同。如果你想要秒,你可以使用ss.
MM - Month with leading 0
M - Month without leading 0
dd - Day with leading 0
d - Day without leading 0
yyyy - 4 Digit year
yy - 2 Digit year
HH - Military Hour with leading 0
H - Military Hour without leading 0
hh - Hour with leading 0
h - Hour without leading 0
mm - Minute with leading 0
m - Minute without leading 0
ss - Second with leading 0
s - Second without leading 0
There are many more. You should check the MSDN documentation for the full reference: https://msdn.microsoft.com/library/zdtaw1bw.aspx
还有更多。您应该查看 MSDN 文档以获取完整参考:https: //msdn.microsoft.com/library/zdtaw1bw.aspx
回答by Rob Rodi
Try using the formatting parameter in ToString
尝试使用格式参数 ToString
[DateTime]::Now.ToString("hh:mm")
回答by fguchelaar
You should check out MSDN's Standard Date And Time Format Strings
您应该查看 MSDN 的标准日期和时间格式字符串
回答by Farouk ElKhabbaz
if you only want the hours and minutes as separated value you can use
如果你只想要小时和分钟作为分隔值,你可以使用
DateTime.Now.Hour.ToString("00.##") + ":" + ateTime.Now.Minute.ToString("00.##");

