How to produce DateTimeOffset string from Noda Time OffsetDateTime in a default for a current culture format?

StackOverflow https://stackoverflow.com//questions/23019131

Question

Suppose I have Noda Time LocalDateTime myLocalDateTime and Offset myOffset variables. To produce a DateTimeOffset string in ISO8601 format I use

var offsetDateTimePattern = OffsetDateTimePattern.Create(OffsetDateTimePattern.ExtendedIsoPattern.PatternText, CultureInfo.InvariantCulture, defaultOffsetDateTime);
var resDateTimeOffsetISO8601 = offsetDateTimePattern.Format(new OffsetDateTime(myLocalDateTime, myOffset));

Now, I also want to produce DateTimeOffset string in a in a default for a current culture format.

For USA it would be like "4/10/2014 3:03:11 PM -07:00". I was thinking about using a combination of "G" pattern with CurrentCulture for DateTime part followed by "m" format for Offset. How would I do that? Something like using "G m" as a pattern text?

var offsetDateTimePatternLocal = OffsetDateTimePattern.Create("G m", CultureInfo.CurrentCulture, defaultOffsetDateTime);
var resDateTimeOffsetCurrentCulture = offsetDateTimePattern.Format(new OffsetDateTime(myLocalDateTime, myOffset));

(Related parsing question was asked here: http://goo.gl/OVeQJT)

Was it helpful?

Solution

I think the best you could do if you want to preserve the culture-aware behavior of the "G" formatter is something like this:

var ldtPattern = LocalDateTimePattern.CreateWithCurrentCulture("G");
var offsetPattern = OffsetPattern.CreateWithCurrentCulture("m");
var result = ldtPattern.Format(localDateTime) + " " + offsetPattern.Format(resOffset);

The problem is that OffsetDateTimePattern doesn't have any culture-aware standard patterns. See the user guide for details. I think this should probably be rectified in a future version.

If you want to format with a fixed pattern, you could. But then you'd need to know the pattern for the culture in advance.

var pattern = OffsetDateTimePattern.Create("M/dd/yyyy h:mm:ss tt o<m>", CultureInfo.InvariantCulture, defaultOffsetDateTime);
var result = pattern.Format(new OffsetDateTime(localDateTime, resOffset));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top