How to get only time from date-time C#

Viewed 415380

Suppose I have the value 6/22/2009 10:00:00 AM. How do I get only 10:00 Am from this date time.

14 Answers

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).

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;
DateTime now = DateTime.Now;

now.ToLongDateString();    // Wednesday, January 2, 2019
now.ToLongTimeString();    // 2:33:59 PM
now.ToShortDateString();   // 1/2/2019
now.ToShortTimeString();   // 2:16 PM
now.ToString();            // 1/2/2019 2:33:59 PM

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

You can use ToString("T") for long time or ToString("t") for short time.

If you're looking to compare times, and not the dates, you could just have a standard comparison date, or match to the date you're using, as in...

DateTime time = DateTime.Parse("6/22/2009 10:00AM");
DateTime compare = DateTime.Parse(time.ToShortDateString() + " 2:00PM");
bool greater = (time > compare);

There may be better ways to to this, but keeps your dates matching.

if you are using gridview then you can show only the time with DataFormatString="{0:t}" example:

    By bind the value:-
<asp:Label ID="lblreg" runat="server" Text='<%#Eval("Registration_Time ", "{0:t}") %>'></asp:Label>

By bound filed:-
<asp:BoundField DataField=" Registration_Time" HeaderText="Brithday" SortExpression=" Registration Time " DataFormatString="{0:t}"/>

You need to account for DateTime Kind too.

public static DateTime GetTime(this DateTime d)
{
    return new DateTime(d.TimeOfDay.Ticks, d.Kind);
}
Related