如何获得当前时间(而不是日期和时间)?

例如:下午5:42:12


当前回答

这是一个可能的解决方案:

DateTime now = DateTime.Now;
string time = now.ToString("T");

其他回答

试试这个。它为我工作在3tier架构Web应用程序。

"'" + DateTime.Now.ToString() + "'"

请记住插入查询中的单引号。

例如:

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() + "')";

行尾的DateTime插入。

timeofday将其作为TimeSpan(从午夜开始)提供给您。

DateTime.Now。ToString("h:mm:ss tt")将其作为字符串提供给您。

DateTime参考:https://msdn.microsoft.com/en-us/library/system.datetime

在我的情况下,我使用下面的代码从DateTime单独获得时间。

var currentDateTime = DateTime.Now; 
var currentTimeAlone = new TimeSpan(currentDateTime.Hour, currentDateTime.Minute,    currentDateTime.Second); 
Console.WriteLine(currentTimeAlone);

希望它能对某些人有所帮助。:)

使用String.Format()的另一个选项

string.Format("{0:HH:mm:ss tt}", DateTime.Now)

试试这个:

DateTime.Now.ToString("HH:mm:ss tt");

对于其他格式,您可以检查这个网站:c# DateTime格式