C# DateTime – Essentials

I’ve worked on a small project for a client recently that heavily relied on working with dates, in different formats, and fortunately C# handles this quite well. Although, if you never worked with C# DateTime before it may get a bit confusing with all the possibilites.

According to Microsoft documentation, a DateTime:

Represents an instant in time, typically expressed as a date and time of day. The DateTime value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar.

Let’s start with the most straightforward ways to generate a DateTime: using “Now” and with the constructor.

var now = DateTime.Now;
// Result: 12/6/2020 7:04:21 PM

var fromCtor = new DateTime(2020, 12, 6, 19, 04, 21);
// Result: 12/6/2020 7:04:21 PM

Parse C# DateTime from String

You can also parse strings into DateTime, which is useful when parsing dates from a text file per example. You can go the easy way and just pass your string as is and hope that it is correct (most of the times it will work):

var stringToParse = "2020/12/06";
var parsed = DateTime.Parse(timeToParse);
// Result: 12/6/2020 12:00:00 AM

You can also enforce a culture. In this case, if your date does not match the culture you have set, you will get an exception.

parsed = DateTime.Parse(timeToParse, new CultureInfo("pt-PT"));

To know more about CultureInfo class you can check Microsoft documentation or you can explore it by yourself. Per example:

CultureInfo ptPT = new CultureInfo("pt-PT");
Console.WriteLine("Culture: " + ptPT.CompareInfo);
Console.WriteLine("Time separator: " + ptPT.DateTimeFormat.TimeSeparator);
Console.WriteLine("Date separator: " + ptPT.DateTimeFormat.DateSeparator);
Console.WriteLine("Short Date Pattern: " + ptPT.DateTimeFormat.ShortDatePattern);
Console.WriteLine("Short Time Pattern: " + ptPT.DateTimeFormat.ShortTimePattern);

It is also possible to parse only time:

timeToParse = "16:12:15";

// This will default the date to current day
parsed = DateTime.Parse(timeToParse, new CultureInfo("pt-PT"));

// This will default the date to Gregorian Date (01/01/0001)
parsed = DateTime.Parse(timeToParse, new CultureInfo("pt-PT"),   DateTimeStyles.NoCurrentDateDefault);

Using DateTime.Parse() may work on most cases, but beware that if your string is not correct you will get an exception. If you think that could happen, and you prefer to handle the exception then you should use: DateTime.TryParse() or DateTime.TryParseExact().

dateToParse = "2020/12/06";
DateTime parsed;
isParsed = DateTime.TryParse(dateToParse, out parsed);

Console.WriteLine("Success? " + isParsed + " Result: " + parsed);

In this case it will try to parse your string, store the result on the output variable and return True or False wether the parsing was succesfull or not. No exception thrown. You can be more specific with DateTime.TryParseExact() like so:

isParsed = DateTime.TryParseExact(timeToParse, "MM/dd/yyyy hh:mm:ss.fffK", new CultureInfo("pt-PT"), DateTimeStyles.None, out parsed);

Convert C# DateTime to String

Sometimes you may want to convert your DateTime object to a string, on a specific format, and you can easily do it.

var now = DateTime.Now;
var dateAsString1 = now.ToString("yyyy-MM-dd");
var dateAsString2 = $"{now:yyyy-MM-dd--->hh:mm:sstt | HH:mm:ss.fff | K | z / zz / zzz | g}";

You can use DateTime.ToString() method which is the most common one but using string interpolation (dateAsString2) also looks good! When specifying the format in which you want the date to be converted to string you use Format Specifiers. On the example above I’ve used the most common ones:

hHour (12-hour clock)
HHour (24-hour clock)
fFraction of a seconds
KKind (Timezone)
zHour offset from UTC (no leading zero)
zzHour offset from UTC (with leading zero)

Operations with C# DateTime

Sometimes you may need to add or subtract to a DateTime, and C# got you covered. It cannot get easier than that! 😁

var now = DateTime.Now;
var addDay = now.AddDays(1);
var subtractDay = now.AddDays(-1);

Compare C# DateTimes

DateTime objects can easily be compared using DateTime.CompareTo() method. DateTime.CompareTo() simply returns and int as result. If dates are equal it returns 0, if instance is latert than the specified DateTime to compare it returns 1 and if earlier it returns -1.

var now = DateTime.Now;
var yesterday = now.AddDays(-1);
var tomorrow = now.AddDays(1);

var result1 = now.CompareTo(yesterday);
var result2 = now.CompareTo(tomorrow);
var result3 = now.CompareTo(now);

// result1 = 1
// result2 = -1
// result3 = 0

With this you should have everything you need for most use cases. But I encourage you to try it on your own and maybe explore a bit more.

If there is anything you think would be important to be here, let me know! 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *