Mikkel R. Lund
Mikkel R. Lund

Reputation: 2627

Optional seconds when serializing NodaTime.LocalTime?

Is it possible to make a pattern for NodaTime's LocalTime, which matches the ISO 8601 standard for times? That is, can you make (minutes and) seconds optional, like you can make fractional seconds optional? I wish to be able to always have hours and minutes, but add everything else only when needed.

Upvotes: 2

Views: 380

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241693

This doesn't exist in NodaTime currently, nor does it exist as an option for the built in DateTime and DateTimeOffset objects.

Probably the best you could do is to create two patterns and add some logic for which to use.

var p1 = LocalTimePattern.ExtendedIsoPattern;
var p2 = LocalTimePattern.CreateWithInvariantCulture("HH:mm");

// formatting
LocalTime t = // your input
var p = t.Second == 0 && t.TickOfSecond == 0 ? p2 : p1;
string s = t.Format(p);

// parsing
string s = // your input
var result = p1.Parse(s);
if (!result.Success)
    result = p2.Parse(s);
if (!result.Success)
    // throw some exception, etc.
LocalTime t = result.Value;

Upvotes: 1

Related Questions