C# 仅获取日期时间的小时/分钟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11107465/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 16:30:02  来源:igfitidea点击:

Getting only hour/minute of datetime

c#

提问by DantheMan

Using C#, I have a datetimeobject, but all I want is the hour and the minutes from it in a datetime object.

使用 C#,我有一个datetime对象,但我想要的只是日期时间对象中的小时和分钟。

So for example: if I have a DateTimeobject of July 1 2012 12:01:02All I want is July 1 2012 12:01:00in the datetimeobject (so, no seconds).

因此,例如:如果我有一个DateTime的对象July 1 2012 12:01:02我想要的是July 1 2012 12:01:00datetime对象(所以,没有秒)。

采纳答案by Roman Starkov

Try this:

尝试这个:

var src = DateTime.Now;
var hm = new DateTime(src.Year, src.Month, src.Day, src.Hour, src.Minute, 0);

回答by Ribtoks

Just use Hourand Minuteproperties

只是用途HourMinute属性

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

或者您可以使用以下方法轻松将秒归零

var zeroSecondDate = date.AddSeconds(-date.Second);

回答by NominSim

I would recommend keeping the object you have, and just utilizing the properties that you want, rather than removing the resolution you already have.

我建议保留您拥有的对象,只使用您想要的属性,而不是删除您已有的分辨率。

If you want to print it in a certain format you may want to look at this...That way you can preserve your resolution further down the line.

如果你想以某种格式打印它,你可能想看看这个......这样你就可以进一步保持你的分辨率。

That being said you can create a new DateTimeobject using only the properties you want as @romkyns has in his answer.

话虽如此,您可以DateTime仅使用@romkyns 在他的回答中提供的属性来创建新对象。

回答by Sid

Try this:

尝试这个:

String hourMinute = DateTime.Now.ToString("HH:mm");

Now you will get the time in hour:minute format.

现在您将获得小时:分钟格式的时间。