Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only time from date-time C# [closed]

Tags:

c#

datetime

time

You have many options for this:

DateTime dt = DateTime.Parse("6/22/2009 07:00:00 AM");

dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // hour is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock

Helpful Link: DateTime.ToString() Patterns


From a DateTime, you can use .TimeOfDay - but that gives you a TimeSpan representing the time into the day (10 hours).


There is only DateTime type in C# and it consist of both the date and time portion. If you don't care about the Date portion of DateTime, set it to default value like this:

DateTime myTime = default(DateTime).Add(myDateTime.TimeOfDay)

This way you can be consistent across all versions of .NET, even if Microsoft decides to change the base date to something else than 1/1/0001.


You might want to look into the DateTime.ToShortTimeString() method.

Also, there many other methods and properties on the DateTime object that can help you in formating the date or time in any way you like. Just take a look at the documentation.


Try this:

TimeSpan TodayTime = DateTime.Now.TimeOfDay;

There are different ways to do so. You can use DateTime.Now.ToLongTimeString() which returns only the time in string format.