Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With NodaTime, how do I format a ZonedDateTime in current culture

I have a ZonedDateTime and I want to display it such that the datetime is formatted with the short date and short time configured on the workstation followed by the offset (something like... 05/01/2005 02:30 PM -05:00). I expected something like this would work...

var patternDateTimeOffset = 
   ZonedDateTimePattern.CreateWithCurrentCulture("g o<m>", DateTimeZoneProviders.Tzdb);
lblOriginalDateTimeAndOffsetVal.Text = patternDateTimeOffset.Format(zonedDateTime);

BUT, it appears that the "g" is not supported in ZonedDateTimePattern the way it is in LocalDateTimePattern. The code above throws a NodaTime.Text.InvalidPatternException.

I could replace the "g" with "MM/dd/yyyy hh:mm", but then it's not using the current culture.

I could use a LocalDateTimePattern for the datetime and then concatenate the offset using the ZonedDateTimePattern. This works, but seems ugly.

This seems like a pretty common thing. I'm new to NodaTime, so I'm certain I'm missing something. I'm using NodaTime 1.3.1 and targeting .net 4.0. Any help is appreciated.

like image 727
Art L. Avatar asked Aug 03 '15 16:08

Art L.


1 Answers

g is fine as a standard pattern specifier - but only on its own; it can't be part of a custom pattern, which is what you're effectively trying to do here. You're effectively trying to mix and match, which we don't support :(

As well as the options you've already outlined (which I agree will work but are somewhat ugly) you could use

var bclDateFormat = CultureInfo.CurrentCulture.DateTimeFormat;
var localDateTimePattern =
    bclDateFormat.ShortDatePattern + " " + bclDateFormat.ShortTimePattern;
var patternDateTimeOffset = ZonedDateTimePattern.CreateWithCurrentCulture(
    localDateTimePattern + " o<m>",
    DateTimeZoneProviders.Tzdb);

Still not terribly pleasant, admittedly - but that's effectively what g does anyway (uses the two existing short patterns and just space-separates them).

As Matt said, please file a feature request - I'm not sure what the best approach is here, but I'll have a think about it.

like image 173
Jon Skeet Avatar answered Nov 17 '22 18:11

Jon Skeet