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

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

This question is related to c# datetime time

The answer is


You need to account for DateTime Kind too.

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

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


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


This works for me. I discovered it when I had to work with DateTime.Date to get only the date part.

var wholeDate = DateTime.Parse("6/22/2009 10:00:00 AM");
var time = wholeDate - wholeDate.Date;

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.


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.


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.


Try this:

TimeSpan TodayTime = DateTime.Now.TimeOfDay;

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


You can use this

lblTime.Text = DateTime.Now.TimeOfDay.ToString(); 

It is realtime with milliseconds value and it sets to time only.


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.


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 can simply write

string time = dateTimeObect.ToString("HH:mm");

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object