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

例如:下午5:42:12


当前回答

Datetime。TimeOfDay返回一个TimeSpan,可能就是你要找的。

其他回答

试试这个。它为我工作在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插入。

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

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

我也在尝试这个方法,发现这些页面也很有帮助。 首先是主类… https://msdn.microsoft.com/en-us/library/system.datetime (v = vs.110) . aspx

现在ToString方法的一些说明符格式… https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo (v = vs.110) . aspx

例子:

using System;

namespace JD
{
    class Program
    {
        public static DateTime get_UTCNow()
        {
            DateTime UTCNow = DateTime.UtcNow;
            int year = UTCNow.Year;
            int month = UTCNow.Month;
            int day = UTCNow.Day;
            int hour = UTCNow.Hour;
            int min = UTCNow.Minute;
            int sec = UTCNow.Second;
            DateTime datetime = new DateTime(year, month, day, hour, min, sec);
            return datetime;
        }

        static void Main(string[] args)
        {
            DateTime datetime = get_UTCNow();            

            string time_UTC = datetime.TimeOfDay.ToString();
            Console.WriteLine(time_UTC);

            Console.ReadLine();

        }
    }
}

我添加了TimeOfDay方法来显示你得到的默认时间是24小时也就是从午夜开始的时间

你可以使用我的getter方法();: - d

DateTime.Now.TimeOfDay

or

DateTime.Now.ToShortTimeString()

试试这个:

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

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