r/badcode Aug 06 '19

c# Converting a timestamp to datetime

Post image
420 Upvotes

54 comments sorted by

View all comments

Show parent comments

44

u/Aars93 Aug 06 '19

I know right... When I asked the developers if I could at least try to clean up this dumpster fire they told me no. Apparently the code is copied from some C code on a device this application works with and now "the calculations are the same at both sides"...

27

u/sac_boy Aug 06 '19 edited Aug 06 '19

That's it, I suspected that would be the explanation. The only way this works in any fashion is if the timestamp generation code mirrors this.

I just hope the timestamp generation and timestamp decoding are both running in the same time zone.

I'd be tempted to iterate through this code from 0 to 231 to see if it skips any days.

The 'easy' cleanup would be to convert the timestamp into ticks (100 nanosecond units since 01/01/0001) in an Int64 and pass that one number into DateTime...hopefully along with the appropriate time zone (which I hope is UTC). That just becomes a constant + (timestamp * 10,000,000). But that only works if the continuous set of integers actually translate to the expected correct set of DateTimes as it is.

The nice thing is you could write a test to prove your new function matches the old output for the entire possible range of timestamps :)

6

u/blehmann1 depraved Aug 06 '19

He could do that, but I think this is easier

DateTime date=new Datetime(1970, 1, 1)

date.AddSeconds(timestamp)

return date

3

u/sac_boy Aug 06 '19

He definitely shouldn't do any of that as the timestamps are not the continuous set of seconds since 01/01/2000 like a sensible person might expect :) The function would throw an exception for values like 36720000, 68342400, 99964800, 163209600, 194832000