Reputation: 87
I have a DateTime
property, how can i get only the Timepart
?
eg-
[Code]
DateTime DepartureTime {get; set;}
If time is 04/02/2014 5:30:00 PM
, I only want the time(5:30 PM
) part in DateTime
. I don't want it in String
as the return type I want is DateTime
.
Upvotes: 0
Views: 205
Reputation: 11177
You can display the time portion as a string without losing the data type of DateTime
by calling ToShortTimeString()
when you want to display it.
It depends on what you want to do with the time. If you need to do more than display it, the first answer is probably more relevant but there are options depending on your needs.
Upvotes: 1
Reputation: 23083
The property TimeOfDay
of a DateTime
, like
DateTime.Now.TimeOfDay
will return the time part of the DateTime. You must be aware that this property returns a TimeSpan
struct and not a DateTime
. The returned value will count the time of the day since midnight of the same day.
If you want to transform the TimeSpan
back into a DateTime
, there is a constructor that you can use:
var date = DateTime.Now;
var timeAsDateTime = new DateTime(1, 1, 1, date.TimeOfDay.Hours, date.TimeOfDay.Minutes, date.TimeOfDay.Seconds);
Upvotes: 3