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");
Source: Stackoverflow.com