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

例如:下午5:42:12


当前回答

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

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

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

其他回答

试试这个:

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

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

我也在尝试这个方法,发现这些页面也很有帮助。 首先是主类… 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

var CurDate= DateTime.Now;
CurDate.Hour;
CurDate.Minute;
CurDate.Millisecond

计算当前的datetime:

DateTime theDate = DateTime.UtcNow;

string custom = theDate.ToString("d");

MessageBox.Show(custom);

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

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

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