About
In this code snippet, we will take a look at DateTime in C#.
DateTime is used to represent dates and times in code. The DateTime class contains many useful methods to manipulate the date(formatting the date, adding/subtracting years, months, days, hours, …).
Let’s have a look at the code below to see how to use DateTime.
Code:
using System; namespace DateTimeExample { class Program { static void Main(string[] args) { //Get current time. DateTime dateTime = DateTime.Now; Console.WriteLine(dateTime.ToString()); //Set a time. (int year, int month, int day, int hour, int minute, int second) dateTime = new DateTime(2023, 10, 6, 12, 24, 30); Console.WriteLine(dateTime.ToString()); //Add/remove time. dateTime.AddMonths(-1); //Removes 1 month. dateTime.AddDays(1); dateTime.AddHours(1); //... //Format the date. Console.WriteLine("Year: " + dateTime.Year.ToString() + " Month: " + dateTime.Month.ToString()); //or (https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings) Console.WriteLine(dateTime.ToString("yyyy-MM-dd HH:mm:ss")); //year, month, day hour, minutes, seconds //Use a time span to get the time difference. TimeSpan timeDiff = dateTime - DateTime.Now; Console.WriteLine(timeDiff.ToString()); //Parse a string to DateTime. dateTime = DateTime.Parse("2023-05-18 12:00:36"); Console.WriteLine(dateTime.ToString()); Console.ReadLine(); } } }