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?
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.
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.
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.
You can use the ToString
method with the appropriate formatting string:
var time = date.ToString("H:mm");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With