Search code examples
c#datetimedeserializationlocaleyamldotnet

How do I specify the date locale when Dserializing YAML using YamlDotNet?


In a YAML document, I've got a date formatted using an EN-GB locale (so 07/02/2019 is 2nd February 2019)

When I deserialize the document using YamlDotNet, it interprets this as an EN-US date so it stores it as July 2nd 2019

# Date in test.yaml:
date: 07/02/2019

# Code to deserialize document to object:
var myObject= new DeserializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .Build()
                .Deserialize<MyObject>(File.ReadAllText(args[0]));

Is there any way to specify whihc locate should be used when dates should be converted when using DeserializerBuilder?


Solution

  • Turns out I needed to include a call to WithTypeConverter() and explicitly specify the date format.

    This code works:

    new DeserializerBuilder()
       .WithNamingConvention(CamelCaseNamingConvention.Instance)
       .WithTypeConverter(new DateTimeConverter(
           provider: CultureInfo.CurrentCulture, 
           formats: new[] { "dd/MM/yyyy", "dd/MM/yyyy hh:mm" })
       ) 
       .Build()
       .Deserialize<MyObject>(File.ReadAllText(args[0]));