TheDeveloperBlog.com

Home | Contact Us

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

C# DateTime Examples

This C# tutorial uses DateTime. It computes relative dates and uses DateTime constructors and properties.

DateTime. Consider May 2015: this is a point in time, a date.

The DateTime struct can store this information. It makes handing time easier.

Related types. This page covers DateTime methods and properties. TimeSpan indicates a range of time. Format strings can be used to create DateTimes.

TimeSpanFormat

Constructor. With new, we invoke the instance DateTime constructor. The arguments must match a real date that occurred. This is a validating constructor.

Example: This example writes a DateTime to the console. It also compares a DateTime against the Today value.

Based on:

.NET 4.5

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(2014, 1, 18);
	Console.WriteLine(value);
	Console.WriteLine(value == DateTime.Today);
    }
}

Output
    The second line depends on the local date on your computer.

1/18/2014 12:00:00 AM
True

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/2014 12:00:00 AM
Yesterday: 11/29/2014 12:00:00 AM

Tomorrow. To figure out tomorrow, we add one using the Add() method. This is useful for using 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, meaning 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/2014 12:00:00 AM
Tomorrow: 12/1/2014 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

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

Elapsed. Next, 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, ElapsedDateTime Subtract

Methods. Many DateTime methods receive double type arguments. A double is a numeric type used like an int. Doubles can store decimal places.

Double

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

AddDays: Receives a double integer, which adds or subtracts days. We can use AddHours, AddMinutes, AddSeconds and more.

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

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

GetDaylightSavingTime: Daylight saving time is what we get for letting our politicians pretend to be scientists. Not useful in Arizona.

IsLeapYear: Leap years have 29 days in February. Leap year is here to make programmers' lives hard and has little other impact.

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

FromOADate. Dates are stored in many formats. MS Excel stores dates in a special numeric format. We use FromOADate to read in these dates. And we can output this format with ToOADate.

FromOADate

Tip: FromOADate and ToOADate are useful for converting Excel dates to C# dates. May also be useful for Visual FoxPro or Microsoft Access.

Excel

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.ParseDateTime.TryParse

ToString. A DateTime can be converted into a string. This helps when displaying, writing or post-processing. With ToString we easily format a DateTime struct as text.

Note: These methods include ToString, ToLongDateString, ToLongTimeString, ToShortDateString and ToShortTimeString.

Often: We must experiment to find the most appropriate method. This is usually the most compatible one.

Months, days. These examples deal with using months and days. We access the Month property. We get all of the days of the week. And we store arrays of all months and days.

MonthDayOfWeekMonth, Day Arrays

Properties. Let's look at properties on the DateTime type. These properties, also listed at MSDN, 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.

Now, UtcNow: These return the current DateTime, with all of the fields correctly filled. DateTime.Now is a useful property.

DateTime.Now

Today: Gets the current date in the form of a DateTime instance. The Today property contains no time information.

DateTime.Today

Null. We can never have a null DateTime instance. The DateTime is a value type, not a reference type, but we can use a nullable DateTime. We can also special-case MinValue.

MinValueNullable DateTime

TimeZone. We all live in different locations. With TimeZone we can easily access information about time zones. Sadly TimeZone is not used in most programs.

TimeZone

Format. We format DateTime instances when we want to store the DateTime in a text representation. Humans read text, not bytes in structs.

Filename, DateTimepubDate, RSSDateTime.Parse, SQL

Pretty: We show how to format DateTime values in more complex ways. We format DateTimes in a "pretty" way.

Pretty Date

24 hours: It is possible to format times on a 24-hour clock format. This article is not ideal.

24-Hour Time Formats

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.

StopwatchStopwatch: Benchmarking

Algorithms. Once I complete my time machine I will post it here. Until then, this section covers some unusual ways to use DateTime. We optimize DateTime.

Closest DateDateTime PerformanceSort DateTimes

Time is a complex subject. But with DateTime and TimeSpan we represent it with relative ease in our programs. These types, implemented as structs, are value types, not reference types.


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