Datetime In C#

We employ the DateTime class in C# for handling date and time operations.

We have the ability to customize the date and time display in various formats using the properties and methods provided by the DateTime class.

The DateTime value falls within the range from 12:00:00 AM on January 1, 0001, to 11:59:59 PM on December 31, 9999 AD.

Here we will demonstrate the process of generating DateTime objects in C#.

We have various methods to instantiate the DateTime object. This object encompasses attributes such as Time, Locale, Date, Localization, and Milliseconds.

Here is a code snippet demonstrating different ways in which the DateTime structure can be used to instantiate DateTime objects.

Example

// From DateTime create the Date and Time
   DateTime DOB= new DateTime(19, 56, 8, 12, 8, 12, 23);
// From String creation of DateTime
            string DateString= "8/12/1956 7:10:24 AM";
            DateTime dateFromString =
                DateTime.Parse(DateString, System.Globalization.CultureInfo.InvariantCulture);
            Console.WriteLine(dateFromString.ToString());
// Empty DateTime  
            DateTime EmpDateTime= new DateTime();
// Just date  
            DateTime OnlyDate= new DateTime(2002, 10, 18);
// DateTime from Ticks  
            DateTime OnlyTime= new DateTime(10000000); 
// Localization with DateTime
            DateTime DateTimewithKind = new DateTime(1976, 7, 10, 7, 10, 24, DateTimeKind.Local); 
// DateTime with date, time and milliseconds  
            DateTime WithMilliseconds= new DateTime(2010, 12, 15, 5, 30, 45, 100);

Properties of DateTime in C#

The DateTime class includes properties for both Date and Time. These properties allow us to access and manipulate specific date and time values. Additionally, DateTime class also provides properties such as Hour, Minute, Second, Millisecond, Year, Month, and Day for more detailed time-related operations.

The other properties of DateTime are:

  • We can get the name of the day from the week with the help of the DayOfWeek property.
  • To get the day of the year, we will use DayOfYear property.
  • To get time in a DateTime, we use TimeOfDay property.
  • Today property will return the object of the DateTime, which is having today's value. The value of the time is 12:00:00
  • The Now property will return the DateTime object, which is having the current date and time.
  • The Utc property of DateTime will return the Coordinated Universal Time (UTC).
  • The one tick represents the One hundred nanoseconds in DateTime. Ticks property of the DateTime returns the number of ticks in a DateTime.
  • The Kind property returns value where the representation of time is done by the instance, which is based on the local time, Coordinated Universal Time (UTC). It also shows the unspecified default value.

In this instance, we will demonstrate how to utilize the features of the DateTime class within C# code.

Example:

Example

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DateTimeProperty = new DateTime(1974, 7, 10, 7, 10, 24);
            Console.WriteLine("Day:{0}", DateTimeProperty.Day);
            Console.WriteLine("Month:{0}", DateTimeProperty.Month);
            Console.WriteLine("Year:{0}", DateTimeProperty.Year);
            Console.WriteLine("Hour:{0}", DateTimeProperty.Hour);
            Console.WriteLine("Minute:{0}", DateTimeProperty.Minute);
            Console.WriteLine("Second:{0}", DateTimeProperty.Second);
            Console.WriteLine("Millisecond:{0}", DateTimeProperty.Millisecond);

            Console.WriteLine("Day of Week:{0}", DateTimeProperty.DayOfWeek);
            Console.WriteLine("Day of Year: {0}", DateTimeProperty.DayOfYear);
            Console.WriteLine("Time of Day:{0}", DateTimeProperty.TimeOfDay);
            Console.WriteLine("Tick:{0}", DateTimeProperty.Ticks);
            Console.WriteLine("Kind:{0}", DateTimeProperty.Kind);
        }
    }
}

Output:

The <style> component consists of a placeholder diagram with a custom background created using a linear gradient. This diagram is enclosed within a border with rounded corners for a visually appealing look. With a generous padding of 40 pixels, the content within the placeholder has ample space to breathe. Positioned centrally on the page, the diagram maintains a neat and organized appearance. Additionally, the placeholder includes an icon that is 3 rem in size, adding a visual element to the design. The accompanying text within the placeholder is styled in a subtle shade of gray (#9ca3af) and is set at a font size of 1 rem for clear readability.

Addition and Subtraction of the DateTime in C#

The DateTime structure offers functions for incrementing and decrementing dates and times within DateTime objects. It allows us to perform date arithmetic by adding or subtracting dates within the DateTime structure. When working with DateTime objects, TimeSpan structure is employed for performing addition and subtraction operations.

For performing addition and subtraction operations with date and time values, the DateTime object provides the Add and Subtract methods. Initially, we instantiate a TimeSpan object with the specific values representing the duration, which we then apply with the Add and Subtract methods.

Here we are developing a script that will perform addition and subtraction operations on dates, specifically adding 3 days and subtracting 30 days from the current date, and then outputting the resulting date on the console.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime Day = DateTime.Now;
            TimeSpan Month = new System.TimeSpan(30, 0, 0, 0);
            DateTime aDayAfterAMonth = Day.Add(Month);
            DateTime aDayBeforeAMonth = Day.Subtract(Month);
            Console.WriteLine("{0:dddd}", aDayAfterAMonth);
            Console.WriteLine("{0:dddd}", aDayBeforeAMonth);
        }
    }
}

The DateTime structure includes functions for incrementing years, days, hours, minutes, and seconds.

To include various components into the DateTime object, the Add method is employed.

Example

// To Add the Years and Days  
   day.AddYears(2);
   day.AddDays(12);
// Add Hours, Minutes, Seconds, Milliseconds, and Ticks  
   Day.AddHours(4.25);
   day.AddMinutes(15);
   day.AddSeconds(45);
   day.AddMilliseconds(200);
day.AddTicks(5000);

The DateTime class does not include a subtract method. To subtract a specific component from a DateTime object, we can utilize the subtract method exclusively. For instance, if we want to deduct 12 days from a DateTime object, we can instantiate another DateTime or TimeSpan object with a duration of 12 days and then subtract this object from the original DateTime. Alternatively, we can also use the minus operator to subtract one DateTime or TimeSpan from another DateTime.

Now, we are going to generate a code snippet that enables us to instantiate DateTime objects and perform subtraction operations between DateTime instances and TimeSpan objects. Within the code, we will specifically demonstrate how to subtract hours, days, or any other components from the DateTime object.

Example

DateTime DOB = new DateTime(2000, 10, 20, 12, 15, 45);
DateTime SubtractDate = new DateTime(2000, 2, 6, 13, 5, 15);

// Use the TimeSpan with 10 days, 2 hrs, 30 mins, 45 seconds, and 100 milliseconds  
TimeSpan ts = new TimeSpan(10, 2, 30, 45, 100);

// Subtract the DateTime  
TimeSpan Different = DOB.Subtract(SubtractDate);
Console.WriteLine(Different.ToString());

// Subtract the TimeSpan  
DateTime Different2 = DOB.Subtract(ts);
Console.WriteLine(Different2.ToString());

// Subtract 10 Days by creating the object SubtractedDays
 DateTime SubtractedDays = new DateTime(DOB.Year, DOB.Month, DOB.Day - 10);
 Console.WriteLine(SubtractedDays.ToString());

 // Subtract hours, minutes, and seconds with creating the object HoursMinutesSeconds
 DateTime HoursMinutesSeconds = new DateTime(DOB.Year, DOB.Month, DOB.Day, DOB.Hour - 1, DOB.Minute - 15, DOB.Second - 15);
Console.WriteLine(HoursMinutesSeconds.ToString());

Searching of the Days in the Month

To determine the number of days in a specific month, we employed the static DaysInMonth function. This method accepts numerical values ranging from 1 to 12 as its input parameter.

Here we are going to create a script that determines the total number of days in a specific month.

Here we are determining the number of days in February of the year 2020. The result will be 28 days.

Example

int NumberOfDays = DateTime.DaysInMonth(2004, 2);
Console.WriteLine(NumberOfDays);

By employing the identical approach, we can determine the overall count of days within a year. To achieve this, we will utilize the function DaysInYear.

Example

private int DaysInYear(int year)
            {
                int DaysIN= 0;
                for (int j = 1; j <= 12; j++)
                {
                    DaysIN += DateTime.DaysInMonth(year, j);
                }
                return DaysIN;
            }

Comparison of two DateTime in C#

The comparer static function is employed to compare two datetime objects. When the datetime objects are identical, the outcome will be 0. In case the first datetime is before the other, the result will be a negative value; otherwise, the first datetime will be later.

Next, we will demonstrate the contrast between the two datetime instances in C#.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DateOfFirst = new DateTime(2002, 10, 22);
            DateTime DateOfSecond = new DateTime(2009, 8, 11);
            int result1 = DateTime.Compare(DateOfFirst, DateOfSecond);

            if (result1 < 0)
                Console.WriteLine("Date of First is earlier");
            else if (result1 == 0)
                Console.WriteLine("Both dates are same");
            else
                Console.WriteLine("Date of First is later");

        }
    }
}

Output:

The <style> component includes a CSS class called "placeholder-diagram". This class defines the styling properties such as background color, border radius, padding, margin, and text alignment. Within this class, there are two nested classes: "placeholder-icon" for setting the font size and margin of an icon, and "placeholder-text" for defining the color and font size of the text content. This structured approach helps maintain consistency and organization in the design of elements.

CompareTo Method

The CompareTo method is employed to compare two dates by assigning the DateTime or object within this method.

To evaluate the two DateTime objects, we employed the CompareTo method. Presented below is a C# script for comparing DateTime objects.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DateOfFirst = new DateTime(2001, 10, 20);
            DateTime DateOfSecond = new DateTime(2009, 8, 11);
            int ResultOfComparison = DateOfFirst.CompareTo(DateOfSecond);
            if (ResultOfComparison < 0)
                Console.WriteLine("Date Of First is Earlier");
            else if (ResultOfComparison == 0)
                Console.WriteLine("Date of Both are same");
            else
                Console.WriteLine("Date of First is Later");

        }
    }
}

Output:

The CSS code snippet below demonstrates how to style a placeholder diagram. This diagram includes a linear gradient background, a border radius of 12 pixels, 40 pixels of padding, and a 20-pixel margin at the top and bottom. The content is centered within the diagram.

Example

.placeholder-diagram { 
  background: linear-gradient(135deg, #374151 0%, #1f2937 100%); 
  border-radius: 12px; 
  padding: 40px; 
  margin: 20px 0; 
  text-align: center; 
}

.placeholder-diagram .placeholder-icon { 
  font-size: 3rem; 
  margin-bottom: 10px; 
}

.placeholder-diagram .placeholder-text { 
  color: #9ca3af; 
  font-size: 1rem; 
}

Formatting of the DateTime in C#

In C#, we have the flexibility to customize the DateTime object into various string formats according to our requirements.

When working with DateTime formatting, we utilized the GetDateTimeFormats method to retrieve a comprehensive list of DateTime formats tailored to the computer's current culture.

Here is a C# code snippet that generates an array containing strings representing various standard formats.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DateOfMonth = new DateTime(2020, 02, 25);
            string[] FormatsOfDate = DateOfMonth.GetDateTimeFormats();
            foreach (string format in FormatsOfDate)
                Console.WriteLine(format);

        }
    }
}

Output:

The CSS code snippet below illustrates the styling for a placeholder element:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

The CSS code snippet below illustrates the styling for a placeholder diagram:

Example

.placeholder-diagram { background: linear-gradient(135deg, #374151 0%, #1f2937 100%); border-radius: 12px; padding: 40px; margin: 20px 0; text-align: center; }
.placeholder-diagram .placeholder-icon { font-size: 3rem; margin-bottom: 10px; }
.placeholder-diagram .placeholder-text { color: #9ca3af; font-size: 1rem; }

We have the option to overload the GetDateTimeFormats function, where we can pass the format specifier as an argument to convert the DateTime into the specified format. Understanding the DateTime specifiers is crucial to achieving the desired format.

We will demonstrate this using code showcasing the pattern within a table.

Code Pattern
"d" Short date
"D" Long date
"f" Full date time. Short time.
"F" Full date time. Long Time.
"g" Generate date time. Long Time.
"G" General date time. Long Time.
"M","m." Month/day
"O","o" Round trip date/time.
"R","r" RFC1123
"s" Sortable date time.
"t" Sort Time
"T" Long Time
"u" Universal sortable date time.
"U" Universal full date-time.
"Y","y" Year, Month

We will specify the format of the DateTime in the below C# Code.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime FormatOfDate = new DateTime(2020, 02, 25);
            // DateTime Formats: d, D, f, F, g, G, m, o, r, s, t, T, u, U,  
            Console.WriteLine("----------------");
            Console.WriteLine("d Formats");
            Console.WriteLine("----------------");
            string[] DateFormat = FormatOfDate.GetDateTimeFormats('d');
            foreach (string format in DateFormat)
                Console.WriteLine(format);
            Console.WriteLine("----------------");
            Console.WriteLine("D Formats");
            Console.WriteLine("----------------");
            DateFormat = FormatOfDate.GetDateTimeFormats('D');
            foreach (string format in DateFormat)
                Console.WriteLine(format);

            Console.WriteLine("----------------");
            Console.WriteLine("f Formats");
            Console.WriteLine("----------------");
            DateFormat = FormatOfDate.GetDateTimeFormats('f');
            foreach (string format in DateFormat)
                Console.WriteLine(format);

            Console.WriteLine("----------------");
            Console.WriteLine("F Formats");
            Console.WriteLine("----------------");
            DateFormat = FormatOfDate.GetDateTimeFormats('F');
            foreach (string format in DateFormat)
                Console.WriteLine(format);

        }
    }
}

Output:

The <style> section displays a CSS code snippet for a placeholder diagram. The diagram has a background styled with a linear gradient from #374151 to #1f2937, a border radius of 12px, padding of 40px, and a margin of 20px at the top and bottom. The content is centered within the diagram.

Within the placeholder diagram, the placeholder icon has a font size of 3rem and a margin bottom of 10px. The placeholder text is styled with a color of #9ca3af and a font size of 1rem.

The CSS code snippet below illustrates the styling for a placeholder diagram. The diagram includes a background with a linear gradient, border radius, padding, margin, and text alignment properties. Furthermore, it consists of an icon with specific font size and margin, as well as text with defined color and font size.

We can format DateTime objects by specifying a format string within the ToString method. Below is the C# code example demonstrating how to format DateTime using the ToString method.

Example

Console.WriteLine(DateOfFormat.ToString("r"));

Now, we are going to create a C# code snippet that demonstrates the usage of DateTime format specifiers in the ToString method.

The styling for the placeholder diagram includes a linear gradient background with specific color codes, a border radius of 12 pixels, padding of 40 pixels, and vertical margin of 20 pixels. Additionally, the content is centered within the diagram. The placeholder icon has a font size of 3rem and a margin-bottom of 10 pixels, while the placeholder text is styled with a color of #9ca3af and a font size of 1rem.

Get the Leap Year and Daylight-Saving Time

Using C# code, we can determine whether a given year is a Leap Year and also handle Daylight Saving Time.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DateOfTime = new DateTime(2020, 02, 22);
            Console.WriteLine(DateOfTime.IsDaylightSavingTime());
            Console.WriteLine(DateTime.IsLeapYear(DateOfTime.Year));

        }
    }
}

Output:

The CSS code snippet shown below creates a visual placeholder diagram. The diagram includes a background gradient, border radius, padding, margin, and text alignment properties. Additionally, it features an icon and text within the placeholder for enhanced visual representation.

Conversion of string to the DateTime

To transform the string into a DateTime object, we made use of the Parse function. When employing the Parse function, it is imperative that the string being passed adheres to the precise DateTime format. Conversely, to convert a DateTime object into a string, the ToString method is employed.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            string DT = "2020-02-04T20:12:45-5:00";
            DateTime NEWDt = DateTime.Parse(DT);
            Console.WriteLine(NEWDt.ToString());

        }
    }
}

Output:

The <style> component includes a CSS class for a placeholder diagram, which has styling properties such as a background gradient, border radius, padding, margin, and text alignment. Within this diagram, there are specific classes for the placeholder icon and placeholder text, which control the size, spacing, and color of these elements. The placeholder icon typically has a larger font size and a margin below it, while the placeholder text is styled with a smaller font size and a specific color. This structured layout helps in visually representing a temporary or missing content placeholder in a web interface.

Conversion of DateTime in C#

The arrangement of the DateTime comprises straightforward conversion methods that transform the DateTime into various specific types. These methods include ToFileTime, ToLocalTime, ToLongDateString, ToBinary, ToLongTimeString, ToOADate, ToShortDateString, ToShortTimeString, ToString, and ToUniversalTime.

Here we'll use a C# example to demonstrate the conversion of DateTime to a particular type.

Example

using System;
using System. Collections;
using System.Collections.Generic;
using System. Linq;
using System. Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {

            DateTime DOB = new DateTime(2020, 01, 22);
            Console.WriteLine("ToString: " + DOB.ToString());
            Console.WriteLine("ToBinary: " + DOB.ToBinary());
            Console.WriteLine("ToFileTime: " + DOB.ToFileTime());
            Console.WriteLine("ToLocalTime: " + DOB.ToLocalTime());
            Console.WriteLine("ToLongDateString: " + DOB.ToLongDateString());
            Console.WriteLine("ToLongTimeString: " + DOB.ToLongTimeString());
            Console.WriteLine("ToOADate: " + DOB.ToOADate());
            Console.WriteLine("ToShortDateString: " + DOB.ToShortDateString());
            Console.WriteLine("ToShortTimeString: " + DOB.ToShortTimeString());
            Console.WriteLine("ToUniversalTime: " + DOB.ToUniversalTime());

        }
    }
}

Output:

Input Required

This code uses input(). Please provide values below: