DataContractJsonSerializer will output the timezone part (+ zzzz) if your DateTime.Kind is Local OR Unspecified. This behavior is different from the XmlSerializer, which only displays part of the time zone if Kind is Unspecified.
If you're interested in learning the source for the JsonWriterDelegator , which contains the following method:
internal override void WriteDateTime(DateTime value) { // ToUniversalTime() truncates dates to DateTime.MaxValue or DateTime.MinValue instead of throwing // This will break round-tripping of these dates (see bug 9690 in CSD Developer Framework) if (value.Kind != DateTimeKind.Utc) { long tickCount = value.Ticks - TimeZone.CurrentTimeZone.GetUtcOffset(value).Ticks; if ((tickCount > DateTime.MaxValue.Ticks) || (tickCount < DateTime.MinValue.Ticks)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.GetString(SR.JsonDateTimeOutOfRange), new ArgumentOutOfRangeException("value"))); } } writer.WriteString(JsonGlobals.DateTimeStartGuardReader); writer.WriteValue((value.ToUniversalTime().Ticks - JsonGlobals.unixEpochTicks) / 10000); switch (value.Kind) { case DateTimeKind.Unspecified: case DateTimeKind.Local: // +"zzzz"; TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime()); if (ts.Ticks < 0) { writer.WriteString("-"); } else { writer.WriteString("+"); } int hours = Math.Abs(ts.Hours); writer.WriteString((hours < 10) ? "0" + hours : hours.ToString(CultureInfo.InvariantCulture)); int minutes = Math.Abs(ts.Minutes); writer.WriteString((minutes < 10) ? "0" + minutes : minutes.ToString(CultureInfo.InvariantCulture)); break; case DateTimeKind.Utc: break; } writer.WriteString(JsonGlobals.DateTimeEndGuardReader); }
I ran the following test on my machine
var jsonSerializer = new DataContractJsonSerializer(typeof(DateTime)); var date = DateTime.UtcNow; Console.WriteLine("original date = " + date.ToString("s")); using (var stream = new MemoryStream()) { jsonSerializer.WriteObject(stream, date); stream.Position = 0; var deserializedDate = (DateTime)jsonSerializer.ReadObject(stream); Console.WriteLine("deserialized date = " + deserializedDate.ToString("s")); }
which produces the expected result:
original date = 2011-04-19T10:24:39 deserialized date = 2011-04-19T10:24:39
Thus, at some point your date should not be specified or local.
After pulling from the database, convert the view from Unspecified to Utc by calling
entity.Date = DateTime.SpecifyKind(entity.Date, DateTimeKind.Utc);
and don't forget to set the return value of SpecifyKind back to your object, as if I have
source share