C#: How do you get the current time (not date AND time)?
Example: 5:42:12 PM
C#: How do you get the current time (not date AND time)?
Example: 5:42:12 PM
DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight).
DateTime.Now.ToString("HH:mm:ss tt") gives it to you as a string.
datetime.TimeOfDay returns a TimeSpan and might be what you are looking for.
Get the current date and time, then just use the time portion of it.
The Date is the time. Internally things get counted as 'number of seconds since some point in time' which I think is Midnight, 1 January, 1600, or something like that.
Current time with AM/PM designator:
DateTime.Now.ToString("hh:mm:ss tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("hh:mm:ss.fff tt", System.Globalization.DateTimeFormatInfo.InvariantInfo)
Current time using 0-23 hour notation:
DateTime.Now.ToString("HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
DateTime.Now.ToString("HH:mm:ss.fff", System.Globalization.DateTimeFormatInfo.InvariantInfo)
This will show you only the current time, in 24 hour format:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now.ToLongTimeString().ToString());
Console.WriteLine(DateTime.Now.ToShortTimeString().ToString());
Console.ReadLine();
}
}
Regards
K
Another option using String.Format()
string.Format("{0:HH:mm:ss tt}", DateTime.Now)
By the way, I want the same data but in DateTime type, cause this is all for strings right?
Hi guys,
Try this one. Its working for me in 3tier Architecture Web Application. :) (But No use here)
'" + DateTime.Now.ToString() + "'
Please remember the Single Quotes in the insert Query.
For example see my example Insertion.
string Command = @"Insert Into CONFIG_USERS(smallint_empID,smallint_userID,str_username,str_pwd,str_secquestion,str_secanswer,tinyint_roleID,str_phone,str_email,Dt_createdOn,Dt_modifiedOn) values (" + u.Employees + "," + u.UserID + ",'" + u.Username + "','" + u.GetPassword() + "','" + u.SecQ + "','" + u.SecA + "'," + u.RoleID + ",'" + u.Phone + "','" + u.Email + "','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "')";
The DateTime insertion at the end of the line.
Let me know how it is working in your Web apps... ?
Regards