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

例如:下午5:42:12


当前回答

这个会好些,试试这个

    DateTime.Now.ToShortTimeString();

为此,您不需要指定时间的格式。

其他回答

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

DateTime.Now.TimeOfDay

or

DateTime.Now.ToShortTimeString()

开始吧:

 DateTime time = DateTime.Now;
 Console.WriteLine(time.ToString("h:mm:ss tt"));

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

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

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

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