When I save a DateTimeOffest
in my project settings, I'm losing some precision :
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 config 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>
Is there a way to specify some serialization parameters to increase precision ?
I know I can use some workaround, for example by storing the Ticks and the offset value or something like that, but I d'like to know if there's not a better way.
EDIT : More info : I'm using the standard Visual Studio project settings to store my value :
MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp;
MyApp.Settings.Default.Save();
MyApp.Settings
is the class generated by Visual studio when you edit settings in the project properties page.
EDIT 2 : Solution :
Base on the answer of Matt Johnson, this is what I did :
LatestCheckTimestamp
to LatestCheckTimestampString
but not in my codeSettings
:.
public DateTimeOffset LatestCheckTimestamp
{
get { return DateTimeOffset.Parse(LatestCheckTimestampString); }
set { LatestCheckTimestampString = value.ToString("o"); }
}
The new config file now looks like :
<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 still is
MyApp.Settings.Default.LatestCheckTimestamp = initialLatestCheckTimestamp;
MyApp.Settings.Default.Save();
The most reliable way to serialize a DateTimeOffset
is with the RoundTrip pattern, which is specified with the "o"
standard serialization string.
This uses the ISO8601 standard, which is highly interoperable with other systems, languages, frameworks, etc. Your value would look like this: 2013-02-22T14:39:06.0000000+00:00
.
.Net will store fractional seconds to 7 decimals with this format.
If you can show some code of how you are storing and retrieving your app setting, I can show you where to specify the format string. In most cases, its simply .ToString("o")
.