[Dev Tip] Another time usage on .NET

Noda Time is an alternative date and time API for .NET. It helps you to think about your data more clearly, and express operations on that data more precisely.

And basic using:

I was planning on converting these times to UTC/Noda Instants to prevent the need to store all the time zone info with each date in the database.

That’s fine if you don’t need to know the original time zone later on. (e.g. if the user changes time zone, but still wants something recurring in the original time zone).

Anyway, I would separate this out into three steps:

  • Parsing into a LocalDateTime
  • Converting that into a ZonedDateTime
  • Converting that into an Instant

Something like:

// TODO: Are you sure it *will* be in the invariant culture? No funky date
// separators?
// Note that if all users have the same pattern, you can make this a private
// static readonly field somewhere
var pattern = LocalDateTimePattern.CreateWithInvariantCulture("yyyy/MM/dd HH:mm");

var parseResult = pattern.Parse(userSubmittedDateTimeString);
if (!parseResult.Success)
    // throw an exception or whatever you want to do

var localDateTime = parseResult.Value;

var timeZone = DateTimeZoneProviders.Tzdb[userTimeZone];

// TODO: Consider how you want to handle ambiguous or "skipped" local date/time
// values. For example, you might want InZoneStrictly, or provide your own custom
// handler to InZone.
var zonedDateTime = localDateTime.InZoneLeniently(timeZone);

var instant = zonedDateTime.ToInstant();

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