Loss of accuracy when saving the DateTimeOffset parameter in the project settings

When I save DateTimeOffest in my project settings, I lose some precision: Losing precision on DateTimeOffset serialization

The first variable is the original value before serialization. The second is the value after Deserialization.

In fact, my variable is serialized like this in the configuration file:

 <?xml version="1.0" encoding="utf-8"?> <configuration> <userSettings> <MyApp.Properties.Settings> [...] <setting name="LatestCheckTimestamp" serializeAs="String"> <value>02/22/2013 14:39:06 +00:00</value> </setting> [...] </MyApp.Properties.Settings> </userSettings> </configuration> 

Can I specify some serialization options to improve accuracy?

I know I can use some workaround, for example by storing Ticks and offset values ​​or something like that, but I would like to know if there is a better way.

EDIT : More info: I'm using the standard Visual Studio project options to save my value:

 MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp; MyApp.Settings.Default.Save(); 

MyApp.Settings is a class generated by Visual Studio when editing settings on the project properties page.

EDIT 2: Solution :

Based on Matt Johnson's answer, this is what I did:

  • Renamed parameter from LatestCheckTimestamp to LatestCheckTimestampString , but not in my code
  • The following Wrapper has been added to an independent file to complete the partial Settings class:

.

 public DateTimeOffset LatestCheckTimestamp { get { return DateTimeOffset.Parse(LatestCheckTimestampString); } set { LatestCheckTimestampString = value.ToString("o"); } } 

The new configuration file now looks like this:

 <configuration> <userSettings> <MyApp.Properties.Settings> [...] <setting name="LatestCheckTimestampString" serializeAs="String"> <value>2013-02-22T16:54:04.3647473+00:00</value> </setting> </MyApp.Properties.Settings> </userSettings> </configuration> 

... and my code is still

 MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp; MyApp.Settings.Default.Save(); 
+4
source share
1 answer

The most reliable way to serialize DateTimeOffset is the RoundTrip pattern , which is specified in the standard serialization string "o" .

It uses the ISO8601 standard, which is very compatible with other systems, languages, frameworks, etc. Your value will look like this: 2013-02-22T14:39:06.0000000+00:00 .

.Net will store fractional seconds up to 7 decimal places in this format.

If you can show some code of how you store and retrieve the settings of your application, I can show you where to specify the format string. In most cases, just .ToString("o") .

+2
source