简体   繁体   中英

F# JSON Type Provider: Handling DateTime and TimeZone

Let's assume the following sample piece of code:

[<Literal>]
let jsonSample =
   """
   {
      "TimeInterval": {
          "Start" : "2010-01-01",
          "End"   : "2010-01-02"
      }
   }
   """

type MyJson = JsonProvider<jsonSample>

The TypeProvider successfully identifies the type of fields to DateTime, however it automatically sets "DateTimeKind" field to "Local". As a result, my code becomes dependent on the machine it's running on and the timezone set in Windows settings.

When I attempt to roundtrip the following record:

{ "TimeInterval": { "Start" : "2010-01-01", "End" : "2010-01-02" } }

and my machine is set to "Europe/Bern +1", I end up serialising

{ "TimeInterval": { "Start" : "2010-01-01T00:00:00000+01:00", "End" : "2010-01-02T00:00:00000+01:00" } }

Can I change this behavior and instruct the Type Provider to leave DateTime's "Kind" field "Unspecified"?

EDIT:

I do the roundtrip by:

let json = MyJson.Parse inFilePath
use outputStream = new StreamWriter(outFilePath, false)
outputStream.WriteLine (json.JsonValue.ToString())
json.JsonValue.ToString()

I don't think there is a way of configuring time zone handling in the JSON type provider. This is always a nightmare, no matter how you handle it, so I think we'd have to add way too many parameters for this to let people do everything they might need to do.

Unfortunately, my recommendation would be to just change the sample so that you get the value as a string . This will mean you'll have to do the date handling on your own, but it should fix the round-tripping issue.

[<Literal>]
let jsonSample =
   """
   {
      "TimeInterval": {
          "Start" : "handling dates is pain / 2010-01-01",
          "End"   : "handling dates is pain / 2010-01-02"
      }
   }
   """

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM