C# 仅获取日期时间对象的时间

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

Getting only time of a datetime object

c#datetime

提问by aleczandru

I am trying to get only the time of a DateTimeobject.

我试图只获取DateTime对象的时间。

Let's say I have this object:

假设我有这个对象:

 Nullable<DateTime> data = new DateTime(2007,6,15,5 ,23,45);

I tryed using :

我尝试使用:

data.Value.ToShortTimeString()

And I recieve:

我收到:

5:23 AM

I would like to be able to display only 5:23

我希望只能显示 5:23

How can I do that?

我怎样才能做到这一点?

采纳答案by Grant Thomas

You can use the ToStringmethod with the appropriate formatting string:

您可以使用ToString具有适当格式字符串的方法:

var time = date.ToString("H:mm");

回答by Soner G?nül

You can use "H" custom format specifier.

您可以使用 “H”自定义格式说明符

The "H" custom format specifier represents the hour as a number from 0 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted without a leading zero.

“H”自定义格式说明符将小时表示为 0 到 23 之间的数字;也就是说,小时由从零开始的 24 小时制表示,该时钟计算自午夜以来的小时数。单位数小时的格式不带前导零。

Nullable<DateTime> data = new DateTime(2007, 6, 15, 5, 23, 45);
Console.WriteLine(data.Value.ToString("H:mm"));

Output will be;

输出将是;

5:23

Here is a DEMO.

这是一个DEMO.

For more information, check out Custom Date and Time Format Strings

欲了解更多信息,请查看 Custom Date and Time Format Strings

回答by jacob aloysious

        Nullable<DateTime> data = new DateTime(2007, 6, 15, 5, 23, 45);
        var timeofDay   = data.Value.TimeOfDay; // 05:23:45

回答by Adeel

var time = date.ToString("H:mm");

Hhere represents 24 hour time. i.e. 0-23

H这里代表24小时时间。即 0-23

See more format Custom Date and Time Format Strings

查看更多格式自定义日期和时间格式字符串

回答by walther

If you need to get a TimeSpantype, use the property in DateTime class called TimeOfDay. It returns only the "time" part.

如果需要获取TimeSpan类型,请使用 DateTime 类中名为TimeOfDay. 它只返回“时间”部分。

If you need to get a string in that format, using TimeOfDay is an overkill and simply use ToString("hh:mm")to format your output. If you don't want results like 05:40, use ToString("H:mm").

如果您需要以该格式获取字符串,则使用 TimeOfDay 是一种矫枉过正,仅用于ToString("hh:mm")格式化输出。如果您不想要像 那样的结果05:40,请使用ToString("H:mm")

回答by Dylan Slabbinck

strange, it works fine for me, maby it's a setting in visual studio?

奇怪,它对我来说很好用,也许这是 Visual Studio 中的设置?

You can try this

你可以试试这个

Nullable<DateTime> data = new DateTime(2007, 6, 15, 5, 23, 45);
Debug.Write(data.Value.Hour + ":" + data.Value.Minute);