Home >Backend Development >C#.Net Tutorial >Get today's date using DateTime.Today function in C#
Use the DateTime.Today function in C# to get today’s date, specific code examples are required
C# is an object-oriented programming language that provides many built-in Classes and methods to handle dates and times. Among them, the DateTime class has some very useful methods, such as the Today property, which can be used to obtain today's date.
The following is a sample code that demonstrates how to use the DateTime.Today function in C# to get today's date:
using System; class Program { static void Main(string[] args) { // 使用DateTime.Today获取今天的日期 DateTime today = DateTime.Today; // 输出今天的日期 Console.WriteLine("今天的日期是:" + today.ToString("yyyy年MM月dd日")); // 获取今天是星期几 string dayOfWeek = today.ToString("dddd"); Console.WriteLine("今天是星期:" + dayOfWeek); // 获取今年的第几天 int dayOfYear = today.DayOfYear; Console.WriteLine("今天是今年的第" + dayOfYear + "天"); // 判断今天是否为闰年 bool isLeapYear = DateTime.IsLeapYear(today.Year); if (isLeapYear) { Console.WriteLine("今年是闰年"); } else { Console.WriteLine("今年不是闰年"); } // 增加一天后的日期 DateTime tomorrow = today.AddDays(1); Console.WriteLine("明天的日期是:" + tomorrow.ToString("yyyy年MM月dd日")); } }
The above code first uses DateTime.Today to get today's date and save it In a variable today of DateTime type. Next, use the ToString method to format the date into a string of "yyyy year MM month dd day" and use Console.WriteLine to output it. Then, using the same method, you can get the day of the week today is, the day of the year, and determine whether this year is a leap year. Finally, you can use the AddDays method to add one day to today's date, get tomorrow's date, and output it.
Running the above code will output results similar to the following:
今天的日期是:2022年01月01日 今天是星期:星期六 今天是今年的第1天 今年不是闰年 明天的日期是:2022年01月02日
Through this example, you can learn how to use the DateTime.Today function in C# to get today's date, and some others Common operations on date and time. Hope it helps you!
The above is the detailed content of Get today's date using DateTime.Today function in C#. For more information, please follow other related articles on the PHP Chinese website!