With a C# DateTime and Culture I can format to a string with:
DateTime exampleDate = DateTime.Now;
CultureInfo culture = new CultureInfo("fr-FR");
String datetimeFormat = exampleDate.ToString(culture.DateTimeFormat.ShortDatePattern));
How do I achieve the same with NodaTime? I've tried combinations along the lines of (doesn't compile - ToString requires two parameters with NodaTimef):
DateTimeZone timeZone = DateTimeZoneProviders.Tzdb["fr-FR"];
ZonedDateTime nowZonedDateTime = new ZonedDateTime(Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()), timeZone);
String nodaFormat = nowZonedDateTime.LocalDateTime.ToString(culture.DateTimeFormat.ShortDatePattern));
I've also tried combinations around the documentation which indicates I need to use "d" to format to short date (this throws an exception):
String nodaFormat = nowZonedDateTime.LocalDateTime.ToString("d", culture));
What am I missing?
Firstly, there isn't a timezone with the ID of fr-FR in TZDB, did you mean Europe/Paris?
Secondly, ToString actually accepts 2 parameters - a pattern string and an IFormatProvider, which can be your CultureInfo. So you're very nearly there - you just need to pass in the culture as the second argument:
CultureInfo culture = new CultureInfo("fr-FR");
DateTimeZone timeZone = DateTimeZoneProviders.Tzdb["Europe/Paris"];
ZonedDateTime nowZonedDateTime = new ZonedDateTime(Instant.FromDateTimeUtc(DateTime.Now.ToUniversalTime()), timeZone);
String nodaFormat = nowZonedDateTime.LocalDateTime.ToString(culture.DateTimeFormat.ShortDatePattern, culture);
// nodaFormat would be "27/12/2019"
The NodaTime documentation lists two APIs for the, a BCL-based one as described in the answer by @Sweeper and a pattern-based API, which it recommends as the preferred approach. First you create a pattern instance, then you use that pattern to format your LocalDate instance.
var frenchCulture = CultureInfo.CreateSpecificCulture("fr-FR");
var frenchDatePattern = LocalDatePattern.Create("d", frenchCulture);
String nodaFormat = frenchDatePattern.Format(nowZonedDateTime.LocalDateTime);
If you have multiple date to format in the same style you can reuse the same datePatternObject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With