DateTime in C#

WBOY
WBOYOriginal
2024-09-03 15:16:12446browse

In C#, DateTime is a struct. Thus it is of value type and used to represent an instant of time. It is used to represent the date and time of the day. The value of type DateTime ranges between 12:00:00 midnight, January 1, 0001 to 11:59:59 PM, December 31, 9999 A.D.Value of DateTime cannot be null because it is a value type. To initialize a DateTime value, we can call any of the overloads of the DateTime constructor. We can also assign values returned from a property or method to a DateTime object.

Syntax:

Below is the syntax to initialize a new instance of the DateTime structure:

DateTime date_time = new DateTime();

Here, date_time is the user-defined name given to the instance of type DateTime. We have initialized this instance using the ‘new’ operator. In the above syntax, we have used an implicit parameterless constructor to initialize DateTime to its default value. We can also initialize the DateTime instance using any of the overloads of the DateTime constructor.

How Does DateTime Work in C#?

In C#, we can work with DateTime and assign value to a DateTime variable in several ways.

  • We can assign value to a DateTime variable by calling any of the overloads of the DateTime constructor, either the parameterless constructor or the constructor with parameters as shown below:
DateTime dateTime = new DateTime(2020, 2, 8, 7, 32, 56);

The above statement initializes a new instance of the DateTime structure for a particular year, month, day, hour, minute, and second.

  • Here, we have used the below constructor of the DateTime structure:
public DateTime(int year, int month, int day, int hour, int minute, int second);
  • Apart from the one described above, there are ten other constructors available to work with DateTime, which are as follows:
public DateTime(long ticks);
  • Here, ‘ticks’ represents a date and time expressed by the number of hundred nanosecond intervals elapsed since January 1 0001 at 00:00:00.000 in the Gregorian calendar.
public DateTime(long ticks, DateTimeKind kind);
  • Here, ‘kind’ represents a value among the enumeration values, which represents whether ticks specify a local time, coordinated universal time, or none of the above.
public DateTime(int year, int month, int day);
  • In this context, ‘year’ represents a value from 1 to 9999, ‘month’ represents a value from 1 to 12, and ‘day’ represents a value within the range of days in a specific month.
public DateTime(int year, int month, int day, Calendar calendar);
  • Here, ‘calendar’ represents a calendar used to interpret year, month, and day.
public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);
  • Here, ‘millisecond’ represents the milliseconds from 0 to 999.
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar);
public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind);
  • We can assign a DateTime variable the DateTime value returned from a property or method as shown below:
DateTime dateTime = DateTime.Now;

This assigns the current date and time to the DateTime variable.

  • We can parse a DateTime value from its string representation and can assign it to a DateTime variable, as shown below:
string str = "6/2/2020 9:20:40 AM";
DateTime dateTime = DateTime.Parse(str, System.Globalization.CultureInfo.InvariantCulture);

We can perform the above conversion using Parse(), ParseExact(), TryParse(), and TryParseExact() methods.

Examples of DateTime in C#

Here are a few examples of how to parse a string to a DateTime object:

Example #1

Example showing current date and time with tomorrow’s date and time using property and method provided by DateTime:

Code:

using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
public static DateTime GetNextDay()
{
//getting next day using AddDays() method
return DateTime.Now.AddDays(1);
}
public static void Main()
{
//displaying current date and time using 'Now' property of DateTime
Console.WriteLine("Current date and time: {0}", DateTime.Now);
DateTime dateTime = GetNextDay();
Console.WriteLine("Tomorrow date and time: {0}", dateTime);
Console.ReadLine();
}
}
}

Output:

DateTime in C#

Example #2

For example, taking the year as input from the user and then checking if it is a leap year or not using DateTime.IsLeapYear() method.

Code:

using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
public static void Main()
{
try
{
//taking year as input from user
Console.WriteLine("Please enter a year");
int year = Convert.ToInt32(Console.ReadLine());
//checking if entered year is a leap year or not
//using DateTime.IsLeapYear() method
Console.WriteLine("\n Using IsLeapYear() method:");
if (DateTime.IsLeapYear(year))
{
Console.WriteLine(year + " is a leap year");
}
else
{
Console.WriteLine(year + " is not a leap year");
}
//checking if entered year is a leap year or not
//using DateTime.DaysInMonth() method
Console.WriteLine("\n Using DaysInMonth() method:");
if (DateTime.DaysInMonth(year, 2) == 29)
{
Console.WriteLine(year + " is a leap year");
}
else
{
Console.WriteLine(year + " is not a leap year");
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}

Output:

DateTime in C#

Example #3

For example, we are getting the first and the last day of the year.

Code:

using System;
using System.IO;
namespace ConsoleApp4
{
class Program
{
public static void Main()
{
DateTime dateTime = DateTime.Now;
//displaying first day of current year
DateTime firstDay = new DateTime(dateTime.Year, 1, 1);
Console.WriteLine("First day of {0} is {1}", dateTime.Year, firstDay);
//getting first day of next year
DateTime dateTimeNext = new DateTime(dateTime.Year + 1, 1, 1);
//subtracting one day from the first day of next year
//to get the last day of current year
DateTime lastday = dateTimeNext.AddDays(-1);
Console.WriteLine("Last day of {0} is {1}", dateTime.Year, lastday);
Console.ReadLine();
}
}
}

Output:

DateTime in C#

Conclusion

The dateTime structure is used to work with date and time. It is used as a data type to store date and time. DateTime provides properties and methods to work with date and time. DateTime is a structure and of a value type; it cannot be null.

The above is the detailed content of DateTime in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:C# String IndexOf()Next article:C# String IndexOf()