The Simplest NuGet Package

One piece of advice I’d give to new developers over and over again is, “Don’t Repeat Yourself“.

There’s a fragment of code – just a couple of lines – that I’ve written many times. I use it every time I consume JSON timestamps. To avoid writing it again, I’m going to create a tiny NuGet package.

Any API that returns timestamped data probably returns the timestamp as a string of digits that doesn’t look much like a date or time. Here’s part of an API sample response from OpenWeatherMap.org:

{
    "id":88319,
    "dt":1345284000,
    "name":"Benghazi",
    "coord":{"lat":32.12,"lon":20.07},
    ...
}

This API response shows the weather in Benghazi at datetime (“dt”) 1.3 billion o’clock or something.

That ten-digit number is a Unix timestamp, or the number of seconds since the “Unix epoch” (i.e. 00:00:00 UTC on 1 January 1970). Handy. It makes more sense than messing around with time zones or trying to parse one of a million text representations of a date and time, but it’s not intuitive.

My conversion code takes two steps. First, convert the Unix time into “ticks”. A tick is 100 nanoseconds. Ticks are the internal unit used by .NET to represent DateTimes. The second step is to turn the tick count into a DateTimeOffset. Even bulking the code out with XML documentation comments, there’s not much to it.

/// <summary>
/// The Time class contains extension methods for converting from
/// one time unit or format to another. The base unit for conversions
/// it the .NET tick, equal to 100 nanoseconds.
/// </summary>
public static class Time
{
    private const long UnixEpochTicks = 621355968000000000;
    private const long TicksPerSecond = 10000000;

    /// <summary>
    /// Converts from a Unix timestamp to the base unit (.NET ticks).
    /// </summary>
    /// <param name="unixTime">The number of seconds since midnight on 1st January, 1970</param>
    /// <returns>The number of ticks represented by the timestamp</returns>
    public static long FromUnixTime(this long unixTime) => unixTime * TicksPerSecond + UnixEpochTicks;

    /// <summary>
    /// Creates a new DateTimeOffset structure representing the tick count.
    /// </summary>
    /// <param name="ticks">The number of ticks</param>
    /// <param name="offsetTicks">The time zone offset in ticks. Defaults to zero, representing UTC</param>
    /// <returns>A new DateTime structure</returns>
    public static DateTimeOffset ToDateTimeOffset(this long ticks, long offsetTicks = 0) => new DateTimeOffset(ticks, new TimeSpan(offsetTicks));
}

To make sure you get the benefit of all that extra typing, include XML documentation in the build output. This will get included in the NuGet package.

See how to use the conversion with a quick xUnit test.

    [Fact]
    public void ConvertUnixBillenniumToDateTimeOffset()
    {
        long elapsedSeconds = 1000000000;
        var billenniumDateTimeOffset = new DateTimeOffset(2001, 9, 9, 1, 46, 40, TimeSpan.Zero);
        var result = elapsedSeconds.FromUnixTime().ToDateTimeOffset();

        Assert.Equal(billenniumDateTimeOffset, result);
    }

The code, all several lines of it, complete with the word ‘billennium’, is on GitHub: darnton / Units.

Creating the NuGet package is easy. Go to the Package section of the project properties and tick the ‘Generate NuGet package in build’ box. If you want to share it publicly, add your name and select a licence.

A .nupkg file will be created every time you build your project. Copy the package to a local folder so you can use it across all your projects. You can set up a local package source from NuGet Package Manager in Visual Studio. From Settings, add a new package source that points to the folder where you’ve saved the package file.

To publish the package to the world, create an account at nuget.org, or log in with your Microsoft account and upload. My tiny package for converting timestamps is here: Darnton.Units.

Andy Hunt and Dave Thomas gave one of the chapters in The Pragmatic Programmer the title, ‘The Evils of Duplication’. Tip 11 in the book was,

DRY – Don’t Repeat Yourself

This was followed up by Tip 12,

Make It Easy to Reuse

A NuGet package, even if it’s tiny, even if it’s only for your own use, makes it easy to avoid repetition.

One thought on “The Simplest NuGet Package

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s