TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# DateTime Examples

Compute date and time values. Get relative dates and call DateTime constructors and properties.
DateTime. Each day the sun rises—bright light marks a new day. From Earth's surface we view the sun's path. What begins as motion gains meaning as time.
Type info. A .NET developer uses DateTime—with TimeSpan and Stopwatch we manipulate time. Night comes fast in this world. Time must be handled with care.TimeSpanStopwatch
Constructor, new. We call the instance DateTime constructor. The arguments must match a real date that occurred. This is a validating constructor.

Example: The code writes a DateTime to the console. It also compares a DateTime against the Today value.

C# program that uses DateTime constructor using System; class Program { static void Main() { // This DateTime is constructed with an instance constructor. // ... We write it to the console. // ... If this is today, the second line will be True. DateTime value = new DateTime(2017, 1, 18); Console.WriteLine(value); Console.WriteLine(value == DateTime.Today); } } Output 1/18/2017 12:00:00 AM False
Un-representable error. The DateTime constructor validates possible arguments. If we try to create a DateTime that cannot exist, we get an argument exception.
C# program that shows un-representable DateTime using System; class Program { static void Main() { // This will cause an error. DateTime x = new DateTime(-1, 1, 1); } } Output An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Year, Month, and Day parameters describe an un-representable DateTime.
AddDays, Add. We can add values to a DateTime with methods like AddDays, AddMonths and Add() which receives a TimeSpan. The most versatile method is Add(), and we can add any TimesSpan.

Add: The Add method (and Subtract) requires a TimeSpan argument. We must first use the TimeSpan constructor.

AddDays: This method receives a double—it can add or subtract days. We can use AddHours, AddMinutes, AddSeconds and more.

Double

AddTicks: One tick is considered one millisecond. This method might be useful when used with Environment.AddTicks.

C# program that uses Add methods using System; class Program { static void Main() { var year2K = new DateTime(2000, 1, 1); // Update the time with AddDays, AddMonths and Add. var updated = year2K.AddDays(1); Console.WriteLine("ADD 1 DAY: {0}", updated); updated = updated.AddMonths(1); Console.WriteLine("ADD 1 MONTH: {0}", updated); // Add 1 day with Add and TimeSpan. updated = updated.Add(TimeSpan.FromDays(1)); Console.WriteLine("ADD 1 DAY: {0}", updated); } } Output ADD 1 DAY: 1/2/2000 12:00:00 AM ADD 1 MONTH: 2/2/2000 12:00:00 AM ADD 1 DAY: 2/3/2000 12:00:00 AM
Yesterday. Here we subtract one day from the current day. We do this by adding -1 to the current day. This is necessary because no "Subtract Days" method is provided.

Note: The example was run a few years ago. The output will naturally vary depending on the day you run it.

And: DateTime.Today is always set to the machine's local time, which depends on the current system.

C# program that computes yesterday using System; class Program { static void Main() { Console.WriteLine("Today: {0}", DateTime.Today); DateTime y = GetYesterday(); Console.WriteLine("Yesterday: {0}", y); } /// <summary> /// Gets the previous day to the current day. /// </summary> static DateTime GetYesterday() { // Add -1 to now. return DateTime.Today.AddDays(-1); } } Output Today: 11/30/2008 12:00:00 AM Yesterday: 11/29/2008 12:00:00 AM
Tomorrow. To figure out tomorrow, we add one using the Add() method. This is useful with date queries in databases. We use the AddDays method.

Static: GetTomorrow is a static method—it does not require state to be saved. DateTime.Today is also static.

Static

Tip: DateTime.Add uses offsets. It accepts both negative and positive numbers. Here we go back in time.

C# program that uses AddDays using System; class Program { static void Main() { Console.WriteLine("Today: {0}", DateTime.Today); DateTime d = GetTomorrow(); Console.WriteLine("Tomorrow: {0}", d); } /// <summary> /// Gets the next day, tomorrow. /// </summary> static DateTime GetTomorrow() { return DateTime.Today.AddDays(1); } } Output Today: 11/30/2008 12:00:00 AM Tomorrow: 12/1/2008 12:00:00 AM
First day. We use a helper method to find the first day in a year. We use an overloaded method. With overloading, we often can use methods in an easier, clearer way.Overload

Current: If we want the current year, we can call FirstDayOfYear with no parameter. The year from Today will be used.

C# program that gets first day using System; class Program { static void Main() { Console.WriteLine("First day: {0}", FirstDayOfYear()); DateTime d = new DateTime(1999, 6, 1); Console.WriteLine("First day of 1999: {0}", FirstDayOfYear(d)); } /// <summary> /// Gets the first day of the current year. /// </summary> static DateTime FirstDayOfYear() { return FirstDayOfYear(DateTime.Today); } /// <summary> /// Finds the first day of year of the specified day. /// </summary> static DateTime FirstDayOfYear(DateTime y) { return new DateTime(y.Year, 1, 1); } } Output First day: 1/1/2008 12:00:00 AM First day of 1999: 1/1/1999 12:00:00 AM
Last day. Here we find the last day in any year. Leap years make this more complicated, as February may have 28 or 29 days. We must programmatically find the year's length.

Tip: This method is ideal for when you want to count days, as for a database range query for a certain year.

Tip 2: It is better to use the DateTime constructor, rather than DateTime.Parse. This is faster and has clearer syntax.

C# program that finds last day using System; class Program { static void Main() { Console.WriteLine("Last day: {0}", LastDayOfYear()); DateTime d = new DateTime(1999, 6, 1); Console.WriteLine("Last day of 1999: {0}", LastDayOfYear(d)); } /// <summary> /// Finds the last day of the year for today. /// </summary> static DateTime LastDayOfYear() { return LastDayOfYear(DateTime.Today); } /// <summary> /// Finds the last day of the year for the selected day's year. /// </summary> static DateTime LastDayOfYear(DateTime d) { // Get first of next year. DateTime n = new DateTime(d.Year + 1, 1, 1); // Subtract one from it. return n.AddDays(-1); } } Output Last day: 12/31/2008 12:00:00 AM Last day of 1999: 12/31/1999 12:00:00 AM
Now, UtcNow. The Now property returns the current DateTime, with all of the fields correctly filled. UtcNow is Universal Coordinated Time, or Greenwich Mean Time.

Tip: The Now property returns the time as a local time, which means it depends on the time zone of the current computer configuration.

DateTime.Now
C# program that uses DateTime.Now, UtcNow using System; class Program { static void Main() { var now = DateTime.Now; var utc = DateTime.UtcNow; // UTC is Greenwich Mean Time. Console.WriteLine("LOCAL: {0}", now); Console.WriteLine("UTC: {0}", utc); } } Output LOCAL: 3/14/2020 3:17:55 AM UTC: 3/14/2020 10:17:55 AM
Parse. It is possible to parse DateTime instances. This converts a string value into a DateTime. The "Try" methods avoid expensive exceptions on invalid strings.DateTime Format

TryParse: The program uses TryParse in an if-statement. If the parsing is successful, we print the RESULT line.

DateTime.TryParse

Parse: If we know that the string is a correct date, we can use Parse. But this will throw an exception on invalid data.

DateTime.Parse
C# program that uses DateTime.TryParse using System; class Program { static void Main() { string value = "3/13/2020"; // Use TryParse to convert from string to DateTime. if (DateTime.TryParse(value, out DateTime result)) { Console.WriteLine("RESULT: {0}", result); } } } Output RESULT: 3/13/2020 12:00:00 AM
Subtract DateTime. We find the "age" of a certain date, and how long ago it was in time. We can do this with DateTime.Subtract, which will return a TimeSpan.DateTime Subtract

Tip: To get the number of days ago a date occurred, we can use the DateTime.Now property.

DateTime, Elapsed
C# program that uses Subtract method using System; class Program { static void Main() { string value1 = "3/13/2020"; string value2 = "3/14/2020"; // Parse the dates. var date1 = DateTime.Parse(value1); var date2 = DateTime.Parse(value2); // Compute the difference between the 2 dates. var difference = date2.Subtract(date1); Console.WriteLine("DAYS DIFFERENCE: {0}", difference.TotalDays); } } Output DAYS DIFFERENCE: 1
Month property. We access the Month property—this returns an integer from 1 to 12 that indicates the month. The value 3 here indicates the month of March.DateTime.Month
C# program that accesses Month property on DateTime using System; class Program { static void Main() { // Print the month for this date string. var date = DateTime.Parse("3/13/2020"); Console.WriteLine("MONTH: {0}", date.Month); } } Output MONTH: 3
DaysInMonth. Many static methods are also available on the DateTime class. With DaysInMonth we look up the number of days in a month based on the year.
C# program that uses DaysInMonth using System; class Program { static void Main() { int days = DateTime.DaysInMonth(2014, 9); // September. Console.WriteLine(days); days = DateTime.DaysInMonth(2014, 2); // February. Console.WriteLine(days); } } Output 30 28
Error, null. A DateTime cannot be assigned to null. It is a struct, and like an int cannot be null. To fix this program, try using the special value DateTime.MinValue instead of null.
C# program that causes null DateTime error using System; class Program { static void Main() { DateTime current = null; } } Output error CS0037: Cannot convert null to 'DateTime' because it is a non-nullable value type
MinValue example. We can use a special value like DateTime.MinValue to initialize an empty DateTime. This is the same idea as a null or uninitialized DateTime.DateTime.MinValue
C# program that uses DateTime.MinValue using System; class Program { static void Main() { // This program can be compiled. // ... Use MinValue instead of null. DateTime current = DateTime.MinValue; Console.WriteLine("MIN VALUE: {0}", current); } } Output MIN VALUE: 1/1/0001 12:00:00 AM
Nullable. We can never have a null DateTime instance. DateTime is a value type. But we can use a nullable DateTime. We use a question mark "DateTime?" for this type.Nullable

Here: We introduce the TestNullable() method. It receives a nullable DateTime, and uses HasValue and Value to test it.

Example: We begin by creating a nullable DateTime and initializing it to Today. Then we create a null DateTime.

C# program that uses nullable DateTime using System; class Program { static void TestNullable(DateTime? argument) { // Handle nullable DateTime. if (argument.HasValue) { Console.WriteLine("VALUE: {0}", argument.Value); Console.WriteLine("VALUE YEAR: {0}", argument.Value.Year); } else { Console.WriteLine("NULL"); } } static void Main() { // Call method with nullable DateTime. DateTime? value = DateTime.Today; TestNullable(value); DateTime? value2 = null; TestNullable(value2); } } Output VALUE: 5/14/2019 12:00:00 AM VALUE YEAR: 2019 NULL
Benchmark, DateTime cache. Here is a way to optimize DateTime usage. When a method calls DateTime.Now, we can sometimes cache this value. This prevents excessive time queries.

Info: Using DateTime.Now is slower than most property accesses as it must fetch the time from the OS.

Version 1: We get a new time only every 20 accesses. This cache makes sense if the current time is queried millions of times rapidly.

Version 2: While version 2 gets DateTime.Now each time. No caching layer is introduced.

Result: Version 1 is much faster. This approach only works in certain applications (like a web application with many rapid requests).

C# program that times DateTime.Now cache using System; using System.Diagnostics; static class DateTimeNowCache { const int _count = 20; static DateTime _recentTime = DateTime.Now; static int _skipped; public static DateTime GetDateTime() { // Get a new DateTime.Now every several requests. // ... This reduces the number of OS time accesses. _skipped++; if (_skipped > _count) { _recentTime = DateTime.Now; _skipped = 0; } return _recentTime; } } class Program { const int _max = 1000000; static void Main() { // Version 1: use cached DateTime.Now. var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var result = DateTimeNowCache.GetDateTime(); if (result == DateTime.MaxValue) { return; } } s1.Stop(); // Version 2: use DateTime.Now each time. var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var result = DateTime.Now; if (result == DateTime.MaxValue) { return; } } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); } } Output 38.66 ns DateTimeNowCache 616.21 ns DateTime.Now
Methods. Many DateTime methods receive double type arguments. A double is a numeric type used like an int. Doubles can store decimal places.

FromBinary, ToBinary: Parses or creates a binary date. You may have a binary date if you have serialized a date to a file.

FromOADate: Microsoft Excel and Visual FoxPro store dates in a numeric format. We use FromOADate and ToOADate to handle these dates.

FromOADate

GetDaylightSavingTime: Daylight saving time changes the daylight hours depending on the season.

IsLeapYear: Leap years have 29 days in February. This must be accounted for to have correct programs.

ToLocalTime: Normally your dates will be in the local time. You can convert an external DateTime to the local time zone with this.

ToString: This helps when displaying, writing or post-processing. With ToString we easily format a DateTime struct as text.

Properties. The DateTime type contains many properties. These properties are useful abstractions—they return specific aspects of your DateTime.

Date: This returns only the date component of the DateTime. It has the "time value set to 12 midnight (00:00:00)."

Day, Month, Year: These return a component of the time. Note that this is not the interval since any other date.

DayOfWeek: We can access the day of the week from any DateTime. This is encoded as a DayOfWeek enum value.

DayOfWeek

Now, Today: Now returns the current time, while Today returns just the current day without the time in the day.

DateTime.Today
TimeZone. We all live in different locations. With TimeZone we can easily access information about time zones. TimeZone is not used in most programs.TimeZone
Custom methods. Often we cannot use DateTime methods directly—we must somehow change or modify data when using DateTime. Many custom solutions can work with DateTime.

Pretty printing: Formats DateTime values in more complex ways. Displays DateTimes in a "pretty" way—for example, like "90 seconds ago."

Pretty Date

24-hour clock: It is possible to format times on a 24-hour clock format. This is sometimes called military time.

24-Hour Time Formats

Closest date: How can we compute the distance of DateTimes? With some logic we can find the closest date to any specific date.

Closest Date

File names: We can store DateTime information in a file name by using string formatting methods.

Filename, DateTime
Timer. With this class, we create a recurrent event, based on an interval. Timer helps monitor long-running processes such as websites.Timer
Stopwatch. If we need to benchmark a program, we use the Stopwatch. For some types of programs, we can use Stopwatch to measure startup time.
Sort. An array or List of DateTime structs can be sorted. This will go from low to high (early to later) in an ascending sort by default.Sort DateTimes
A summary. Time is a complex subject. But with DateTime and TimeSpan we represent it with relative ease in our programs. These types are value types (like ints) not reference types.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf