Tuesday, 9 September 2025

DateTime Functions in C# and .NET

Leave a Comment

In .NET, what is DateTime?
A.NET struct called DateTime is used to express dates and times with a precision of 100 ticks, or nanoseconds. System Assembly namespace: mscorlib.dll

Creating DateTime Instances

// Current date and time (system clock)
DateTime now = DateTime.Now;

// Current UTC time
DateTime utcNow = DateTime.UtcNow;

// Only current date, time set to 00:00:00
DateTime today = DateTime.Today;

// Specific date
DateTime specificDate = new DateTime(2025, 9, 8); // YYYY, MM, DD

// Specific date and time
DateTime specificDateTime = new DateTime(2025, 9, 8, 14, 30, 0); // YYYY,MM,DD,HH,MM,SS

Properties of DateTime

PropertyDescriptionExample
DateReturns the date part only (time = 00:00:00)now.Date
DayDay of the month (1-31)now.Day
MonthMonth (1-12)now.Month
YearYear componentnow.Year
DayOfWeekEnum representing day of weekDayOfWeek.Monday
DayOfYearDay number in the year (1-366)now.DayOfYear
TimeOfDayReturns a TimeSpannow.TimeOfDay
Hour, Minute, Second, MillisecondComponents of timenow.Hour

Common DateTime Methods

🧾Static Methods

DateTime current = DateTime.Now;

// Parsing
DateTime parsed = DateTime.Parse("2025-09-08");
DateTime parsedExact = DateTime.ParseExact("08-09-2025", "dd-MM-yyyy", null);

// Comparing
int result = DateTime.Compare(DateTime.Now, DateTime.UtcNow); // -1, 0, 1

// Check Leap Year
bool isLeap = DateTime.IsLeapYear(2024);

Instance Methods for Manipulation

DateTime today = DateTime.Today;

DateTime tomorrow = today.AddDays(1);       // Add days
DateTime lastWeek = today.AddDays(-7);      // Subtract days
DateTime nextMonth = today.AddMonths(1);    // Add months
DateTime lastYear = today.AddYears(-1);     // Subtract years
DateTime futureTime = today.AddHours(5);    // Add hours

Comparison Methods

DateTime a = DateTime.Now;
DateTime b = a.AddMinutes(10);

bool isEqual = a.Equals(b);    // false
int compare = a.CompareTo(b);  // -1 (a < b)

bool after = a > b;            // false
bool before = a < b;           // true

Formatting Methods

DateTime now = DateTime.Now;

// ToString with custom format
string formatted = now.ToString("dd/MM/yyyy HH:mm:ss");

// Predefined formats
string longDate = now.ToLongDateString();  // Monday, September 8, 2025
string shortDate = now.ToShortDateString(); // 9/8/2025
string longTime = now.ToLongTimeString();  // 4:25:30 PM
string shortTime = now.ToShortTimeString(); // 4:25 PM

Time Zones

DateTime utcNow = DateTime.UtcNow;

// Convert to local time
DateTime local = utcNow.ToLocalTime();

// Specify kind explicitly
DateTime unspecified = DateTime.SpecifyKind(utcNow, DateTimeKind.Unspecified);

DateTimeOffset (Recommended for Modern Apps)

DateTimeOffset is often preferred because it stores both the date/time and the UTC offset, which avoids ambiguity when working across multiple time zones.

DateTimeOffset dto = DateTimeOffset.Now;
Console.WriteLine(dto.Offset); // e.g., +05:30

Best Practices

  • Prefer DateTime.UtcNow for logging, auditing, and storage — avoid timezone issues.

  • Use DateTimeOffset when time zones matter (multi-region apps).

  • Use TryParse or TryParseExact for safe conversions (avoid exceptions).

  • Always specify a format when serializing dates (ISO 8601 recommended: "yyyy-MM-ddTHH:mm:ssZ").

ASP.NET Core 9.0 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 9.0 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFE.eu, customers can also experience fast ASP.NET Core hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment