Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting only time of a datetime object [duplicate]

Tags:

c#

datetime

I am trying to get only the time of a DateTime object.

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

How can I do that?

like image 705
aleczandru Avatar asked Apr 15 '13 08:04

aleczandru


People also ask

How do you find the time from a date time object?

How to Get the Current Time with the datetime Module. To get the current time in particular, you can use the strftime() method and pass into it the string ”%H:%M:%S” representing hours, minutes, and seconds.

How can I get only the date from datetime format?

ToString() − One more way to get the date from DateTime is using ToString() extension method. The advantage of using ToString() extension method is that we can specify the format of the date that we want to fetch. DateTime. Date − will also remove the time from the DateTime and provides us the Date only.

How do I copy a datetime object?

A copy of DateTime object is created by using the clone keyword (which calls the object's __clone() method if possible). An object's __clone() method cannot be called directly.


2 Answers

You can use the ToString method with the appropriate formatting string:

var time = date.ToString("H:mm");
like image 127
Grant Thomas Avatar answered Nov 12 '22 19:11

Grant Thomas


You can use "H" custom format specifier.

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.

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.

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

like image 23
Soner Gönül Avatar answered Nov 12 '22 21:11

Soner Gönül