Home > Backend Development > C#.Net Tutorial > Get the current time using DateTime.Now function in C#

Get the current time using DateTime.Now function in C#

王林
Release: 2023-11-18 15:14:42
Original
1327 people have browsed it

Get the current time using DateTime.Now function in C#

Use the DateTime.Now function in C# to get the current time

In C# programming, we often need to get the current time. The DateTime.Now function is provided in C# to obtain the current system time. Below I will introduce to you how to use the DateTime.Now function and give specific code examples.

DateTime.Now function returns a DateTime object representing the current date and time. Its usage is very simple, just call the function. The following is an example of getting the current time and outputting it:

using System;

class Program
{
    static void Main()
    {
        // 获取当前时间
        DateTime currentTime = DateTime.Now;

        // 输出当前时间
        Console.WriteLine("当前时间是: " + currentTime.ToString());

        // 获取当前时间的小时、分钟和秒
        int hour = currentTime.Hour;
        int minute = currentTime.Minute;
        int second = currentTime.Second;

        // 输出当前时间的小时、分钟和秒
        Console.WriteLine("当前时间的小时: " + hour);
        Console.WriteLine("当前时间的分钟: " + minute);
        Console.WriteLine("当前时间的秒: " + second);
    }
}
Copy after login

In the above code, we first call the DateTime.Now function to get the current time. Then use the ToString() method to convert the current time into a string and output it to the console. Then we get the hours, minutes, and seconds of the current time through the properties of the DateTime object, and output them to the console.

The running results of the above code are as follows:

当前时间是: 2021/6/15 9:30:25
当前时间的小时: 9
当前时间的分钟: 30
当前时间的秒: 25
Copy after login

Through the above example, we can see that the use of the DateTime.Now function is very simple. You only need to call the function to get the current time. Then we can obtain the year, month, day, hour, minute, second and other information of the time through the properties of the DateTime object.

To summarize, this article introduces how to use the DateTime.Now function in C# to obtain the current system time, and gives specific code examples. Hope this helps everyone.

The above is the detailed content of Get the current time using DateTime.Now function in C#. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template