Time in C#

Our first example demonstrates extensive support for times and durations in C#. Here are some examples:

using System;

class Program
{
    static void Main()
    {
        Action<object> p = Console.WriteLine;

        // We'll start by getting the current time.
        DateTime now = DateTime.Now;
        p(now);

        // You can create a DateTime struct by providing the
        // year, month, day, etc. Times are always associated
        // with a Kind, which is similar to a time zone.
        DateTime then = new DateTime(2009, 11, 17, 20, 34, 58, 651, DateTimeKind.Utc);
        p(then);

        // You can extract the various components of the DateTime
        // value as expected.
        p(then.Year);
        p(then.Month);
        p(then.Day);
        p(then.Hour);
        p(then.Minute);
        p(then.Second);
        p(then.Millisecond);
        p(then.Kind);

        // The day of the week is also available.
        p(then.DayOfWeek);

        // These methods compare two times, testing if the
        // first occurs before, after, or at the same time
        // as the second, respectively.
        p(then < now);
        p(then > now);
        p(then == now);

        // The Subtract method returns a TimeSpan representing
        // the interval between two times.
        TimeSpan diff = now.Subtract(then);
        p(diff);

        // We can compute the length of the duration in
        // various units.
        p(diff.TotalHours);
        p(diff.TotalMinutes);
        p(diff.TotalSeconds);
        p(diff.TotalMilliseconds);

        // You can use Add to advance a time by a given
        // TimeSpan, or with a negative TimeSpan to move backwards.
        p(then.Add(diff));
        p(then.Add(-diff));
    }
}

To run the program, save it as TimeExample.cs and use the C# compiler:

$ csc TimeExample.cs
$ mono TimeExample.exe

This will output various time-related information and calculations. The exact output will depend on the current time when you run the program, but it will demonstrate the various time and duration operations shown in the code.

In C#, we use the DateTime struct for representing a specific point in time, and TimeSpan for representing a duration. These types provide methods and properties for various time-related operations, similar to the Go time package.

The DateTimeKind enum in C# is somewhat analogous to the Location in Go, though it’s more limited (only specifying UTC, local, or unspecified).

C# doesn’t have nanosecond precision for times; the smallest unit is typically a tick (100 nanoseconds) or a millisecond, depending on the method used.

Next, we’ll look at the related idea of time relative to the Unix epoch.