Using Noda Time in .NET

By James Kenny
2 min read

Table of Contents

Noda Time is a Date / Time API for .net. It is more precise on the data and it can make it easier to work with date / times. It also has some extra functionality and is easier to use than the default API.

This is the first part of a series, this will explore other parts of Noda Time in more detail.

In this post we will cover

  • Getting the Time Zones From Noda Time
  • Converting a user date into UTC
  • Converting UTC current time into a users current time

My sample code can be found here

Installing Noda Time

You can install noda time from the package manager. You can get more information on the versions here

PM> Install-Package NodaTime


Noda Time has a TimeZoneInfo class that will allow us to bring back all the time zones

var timeZones = TimeZoneInfo.GetSystemTimeZones();

foreach (var oTimeZone in timeZones)
Console.WriteLine("TimeZone: " + oTimeZone.DisplayName + " Id: " + oTimeZone.Id);

The above code will display all the time zones, with the Id and the Name.

Converting Dates

I want to convert dates from 1 timezone to another. The following code will do just that.

// Set our fictional users time zone
string easternZoneId = "Eastern Standard Time";

// The date they want to schedule the delivery.
var userScheduledTime = new DateTime(2019, 12, 03, 10, 46, 00);

// Load the NodaTimeZone information for the users timezone
TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);

// Convert the Date Time to UTC
var utcTime = TimeZoneInfo.ConvertTimeToUtc(userScheduledTime, easternZone);

Lets walk through what this code is doing

string easternZoneId = "Eastern Standard Time";
var userScheduledTime = new DateTime(2019, 12, 03, 10, 46, 00);

The first section of code we set up our users time zone as "Eastern Standard Time" and we then set a users schedule date time to 10:46 on 03 December 2019.

TimeZoneInfo easternZone = TimeZoneInfo.FindSystemTimeZoneById(easternZoneId);

Then we load our timezone information from NodaTime's TimeZoneInfo.

var utcTime = TimeZoneInfo.ConvertTimeToUtc(userScheduledTime, easternZone);

Our last step is to use NodaTime's ConvertTimeToUTC to convert our users scheduled time, we tell it the TimeZoneInfo for where our user is.

Get Current Time

If we want to get the users current time.

DateTime dNow = DateTime.Now.ToUniversalTime();

var userNowTime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dNow, easternZoneId);

This code gets the current UTC time. And then using Noda Time and our users time zone we are able to get the users current time.

Thanks for reading this post, I've tried to cover the basics of converting with Noda Time, This will be the first of a series of posts on Noda Time and what we can do with it. I'll also explore other areas of the API in more detail.

Tagged in:

.NET, NodaTime, DateTime

Last Update: October 01, 2019

About the Author