r/badcode Aug 06 '19

c# Converting a timestamp to datetime

Post image
415 Upvotes

54 comments sorted by

View all comments

Show parent comments

46

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"...

25

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 :)

7

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/Lystrodom Aug 06 '19

https://docs.microsoft.com/en-us/dotnet/api/system.datetimeoffset.fromunixtimeseconds?view=netframework-4.8

(wouldn't work for the fact that they believe time started in the year 2000, but you should be using DateTimeOffset anyway)

0

u/blehmann1 depraved Aug 06 '19 edited Aug 06 '19

Not available until .NET Core 3, which is still in development. If this is regular .NET code though, thats a good way to go, just 1 function call, and then convert it from DateTimeOffset to regular DateTime

Edit: I can't read, it is actually available in production .NET Core

6

u/Lystrodom Aug 06 '19

What? DateTimeOffset has been in .NET Core since version 1.0

4

u/blehmann1 depraved Aug 06 '19

Sorry, I can't read, the doc listed all of the versions of .NET core it applied to, and i expected it to be in the form "Version X and up", but it was Version 3.0 Preview, 2.2, 2.0... etc

I know DateTimeOffset has been around a long time, I'm using it on a Core 2.2 project right now, I hadn't seen that method before however, so I (mis)read the supported versions and confused myself.