Getting a Fail Trying to Parse a ZonedDateTime from a String Using ZonedDateTimePattern

Viewed 110

I've been learning how to use NodaTime, as I think it is a far superior "all things temporal" library that the handful of structs in the BCL. Reading the docs and experimenting.

This experiment has me flummoxed. I started out just trying to parse a ZonedDateTime. The things I was trying were not successful, so I thought I'd try something which should be "bulletproof". The following code represents that attempt:

Instant thisNow = SystemClock.Instance.GetCurrentInstant();
var timezone = DateTimeZoneProviders.Tzdb["Australia/Brisbane"];

var zonedDateTime = thisNow.InZone(timezone);

var zonePattern = ZonedDateTimePattern.GeneralFormatOnlyIso;

var zoneFormatted = zonePattern.Format(zonedDateTime);

var zoneParseResult = zonePattern.Parse(zoneFormatted);

Console.WriteLine(zoneParseResult.Success ? "parse success" : "parse failure");

So, simply trying to parse back that which you just converted to a string.

The zoneFormatted has the following value 2021-09-04T16:59:08 Australia/Brisbane (+10)

Any ideas what I am doing wrong?
Cheers

1 Answers

Any ideas what I am doing wrong?

You're using ZonedDateTimePattern.GeneralFormatOnlyIso, which is (as the name suggests) only for formatting, not for parsing.

To get a pattern which is able to parse time zones, you need to specify an IDateTimeZoneProvider. The easiest way to do that is to start with a format-only pattern, and use WithZoneProvider:

using NodaTime;
using NodaTime.Text;
using System;

class Program
{
    static void Main(string[] args)
    {
        var pattern = ZonedDateTimePattern.GeneralFormatOnlyIso
            .WithZoneProvider(DateTimeZoneProviders.Tzdb);
        var text = "2021-09-04T16:59:08 Australia/Brisbane (+10)";
        var result = pattern.Parse(text);
        Console.WriteLine(result.Success);
        Console.WriteLine(result.Value);
    }
}
Related