0

In my application i receive Time stamp and in c# code I convert into date and pass this date to execute the stored procedure .My application is placed in server machine. But when this date is printed in log i saw the date is receiving in server one day less. Below is my code to convert from time stamp to date,

DateTime fromDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
fromDate =fromDate.AddMilliseconds(1430159400000).ToLocalTime();

date is : '2015-04-28' But when in server it receive as '2015-04-27'. This i came to know when i print this date in log. What i am doing wrong here!. Any suggessions most welcome.

Regards Sangeetha

Sangeetha
  • 699
  • 5
  • 16
  • 37

2 Answers2

1

Well currently you're converting the UTC timestamp to the system-local time - and presumably your server is in a different time zone to you.

I would strongly advise you to log the UTC timestamp directly, in UTC. Whatever reads your logs can then convert it to a local time in whatever time zone you want, but it's a lot more portable that way:

  • you don't need to know what time zone the server was in in order to understand the logs
  • you can merge logs from multiple servers trivially
  • you don't get any periods of ambiguity where a given local time occurs twice due to a daylight saving transition
  • if you plot aspects of the logs on a graph or something similar, you don't end up with bizarre discontinuities again due to daylight saving transitions
  • your code behaves the same on your dev machine as on your servers

So, you should:

  • Remove the ToLocalTime call
  • Make sure that however you're logging the timestamp includes Z at the end, so that it's clear it's in UTC.
  • Make sure that you use the invariant culture for logging, to avoid conversion to non-Gregorian calendars

If you're storing timestamps in the database, I'd recommend storing those in UTC as well. Some kinds of date/time values are best stored in local time, but timestamps are more global, representing an instant in time, so UTC is a suitable zone to use for storage.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Since you calculate your DateTime based on Unix time, your 1430159400000 milliseconds (1430159400 seconds) generates Mon, 27 Apr 2015 18:30:00 UTC.

And since you calculate your local time with ToLocalTime method, this adds your current time zone offset to this DateTime. I strongly suspect your current machine and your server has different time zones and even your current UTC offset is equal or more then +05:30, that's why your ToLocalTime generates a local time that belongs one day after.

Logging a DateTime values as Local might be ambiguous. You should never do that. You should always store your DateTime as UTC.

Please read the best practices for that kind of processing;

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364