C# DateTime

C# Code Snippets DateTime
Share:

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

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger