1
I am saving in text file a serialized object that contains only fields of type Datetime, however, the date is saving in the wrong way.
I will demonstrate with an example what I am doing.
My Databaseviewmodel object has two Datetime-like fields
[Serializable]
public class DataBaseViewModel
{
public DateTime ultimaAtualizacaoTfs { get; set; }
public DateTime ultimaAtualizacaoSis { get; set; }
}
I add values to my object
var datasBase = new DatasBaseViewModel();
datasBase.ultimaAtualizacaoSis = new DateTime(2015, 11, 9, 15, 10, 10);
datasBase.ultimaAtualizacaoTfs = new DateTime(2015, 11, 9, 15, 11, 11);
So save the object serialized in text
using (Stream stream = File.Open(_pathToDatasBase, FileMode.Create))
using (StreamWriter streamWriter = new StreamWriter(stream))
{
streamWriter.WriteLine(new JavaScriptSerializer().Serialize(dataBase));
}
Another time, I will read the contents of my text file.
var datasBase = new DataBaseViewModel();
using (Stream stream = File.Open(_pathToDatasBase, FileMode.Open))
using (StreamReader streamReader = new StreamReader(stream))
{
datasBase = new JavaScriptSerializer().Deserialize<DataBaseViewModel>(streamReader.ReadToEnd());
}
After reading and deserializar, my object is with the incorrect date, different from what I saved.
In that case, I saved the dates 09/11/2015 15:10:10
and 09/11/2015 15:11:11
and in the deserialized object I have the dates 09/11/2015 17:10:10
and 09/11/2015 17:11:11
.
The text file with the serialized object is saved this way:
{"ultimaAtualizacaoTfs":"\/Date(1447089071000)\/","ultimaAtualizacaoSis":"\/Date(1447089010000)\/"}
It is certainly a time zone problem. To know why you would need to see more context. I don’t know if I’m missing something, but if you save it one way and read it the same, it shouldn’t be a problem.
– Maniero
Must be using utc date... try to change
new StreamReader(stream,Encoding.UTF8))
– Marco Souza
You have this answer here that I may be able to help you http://answall.com/questions/931/data-incorrect
– Filipe Oliveira
Exactly @bigown. I’m saving UTC-2 (local) and deserializing UTC. I converted the date the moment I read it: datesBase.ultimaryAtualizacaoTfs.Tolocaltime()
– Pedro Camara Junior
There’s no conversion in your code. I think the problem is somewhere else and without posting something that we can see and test, it is difficult to help.
– Maniero
The code is just that, I think at the time of deserializar should assume that it is UTC, because at no time before saving I change the time zone.
– Pedro Camara Junior
Could be, why I think every date should be UTC.
– Maniero