C# DateTime

0 comments

In .NET Framework, a DateTime structure represents dates and times. We use DateTime to work with dates, times, and both. The value of DateTime is between 12:00:00 midnight, January 1, 0001 to 11:59:59 P.M., December 31, 9999 A.D.
This chapter is all about date and time representation in .NET framework. The chapter covers the following topics:

  • How to create a DateTime
  • Understand DateTime properties
  • How to add and subtract date and time using DateTime
  • Find days in a month and year
  • How to compare two dates, times or DateTime
  • How to format dates and times
Creating DateTime
There are several ways to create a DateTime object. A DateTime object can have a Date, Time, Localization, culture, milliseconds, and kind.
The code in Listing 1 uses various constructors of DateTime structure to create DateTime objects.
// Create a DateTime from date and time
DateTime dob = new DateTime(1974, 7, 10, 7, 10, 24);

// Create a DateTime from a String
string dateString = "7/10/1974 7:10:24 AM";
DateTime dateFromString =
    DateTime.Parse(dateString, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(dateFromString.ToString());

// Empty DateTime
DateTime emptyDateTime = new DateTime();

// Just date
DateTime justDate = new DateTime(2002, 10, 18);

// DateTime from Ticks
DateTime justTime = new DateTime(1000000);

// DateTime with localization
DateTime dateTimeWithKind = new DateTime(1974, 7, 10, 7, 10, 24, DateTimeKind.Local);

// DateTime with date, time and milliseconds
DateTime dateTimeWithMilliseconds = new DateTime(2010, 12, 15, 5, 30, 45, 100);

READ MORE >>

0 comments: