What are the methods for getting time in C#?

There are several methods to get the time in C#.

  1. Get the current system time using the static method Now of the DateTime class.
DateTime currentTime = DateTime.Now;
  1. Obtain the current UTC time of the system by using the static method UtcNow of the DateTime class.
DateTime currentUtcTime = DateTime.UtcNow;
  1. Create a specific time by using the constructor of the DateTime class.
DateTime specifiedTime = new DateTime(2022, 12, 31, 23, 59, 59);
  1. Retrieve specific time information such as year, month, day, hour, and minute using the properties of the DateTime class.
int year = currentTime.Year;
int month = currentTime.Month;
int day = currentTime.Day;
int hour = currentTime.Hour;
int minute = currentTime.Minute;
  1. Format the time into a specified string using the ToString method of the DateTime class.
string formattedTime = currentTime.ToString("yyyy-MM-dd HH:mm:ss");

These are some common methods for getting time in C#, choose the appropriate method based on specific needs in development.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds