How do you get the current time of day?

后端 未结 20 2518
长发绾君心
长发绾君心 2020-11-28 18:40

How do you get the current time (not date AND time)?

Example: 5:42:12 PM

相关标签:
20条回答
  • 2020-11-28 19:29

    I'm experimenting with this also and find these pages helpful as well. First the main class... https://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx

    Now some specifier formats for the ToString method... https://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo(v=vs.110).aspx

    Example:

    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();
    
            }
        }
    }
    

    I threw that TimeOfDay method in there just to show that you get a default of 24 hour time as is stated "the time from midnight"

    You may use my geter method(); :-D

    0 讨论(0)
  • 2020-11-28 19:31

    I think this code will solve your problem

    DateTime.Now.ToString("HH:mm")
    
    0 讨论(0)
  • 2020-11-28 19:32
    DateTime.Now.TimeOfDay
    

    or

    DateTime.Now.ToShortTimeString()
    
    0 讨论(0)
  • 2020-11-28 19:33

    This can be a possible solution:

    DateTime now = DateTime.Now;
    string time = now.ToString("T");
    
    0 讨论(0)
  • 2020-11-28 19:34

    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

    0 讨论(0)
  • 2020-11-28 19:37

    DateTime.Now.TimeOfDay gives it to you as a TimeSpan (from midnight).

    DateTime.Now.ToString("h:mm:ss tt") gives it to you as a string.

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

    0 讨论(0)
提交回复
热议问题