DateTime rounding struggles
While writing tests for my api, I've noticed an interesting issue.
My assertion comparing an object returned by an api with a reference in the database kept failing, while they were querying the same object in the database.
The difference was apparently a microsecond property of
DateTime
that did not make it through Json serialization, while EF core returned the full value, thus the objects were different.
Is there a way i could modify serialization properties in asp.net api to transmit the full timestamp without sacrificing data integrity? Or somehow round value to disregard the millisecond property?8 Replies
Json itself doesn't care for dates. You can serialize it as a string if you want, as long as your consistent on the other end. I would recommend staying with a good ISO though.
ISO8601 represent
Your best bet would be to either:
1. Compare Unix timestamps since they have a maximum precision of seconds
2. Write an extension method that strips microseconds and compare that
3. Write an extension method that compares only the desired elements of the DateTime
unix timestamp miliseconds are also very often and BCL has apis for those
and I've seen quite a few apis use unix miniseconds for json too
Sure. I've seen that too. I wouldn't lynch anyone for doing that, but I think it doesn't bring anything positive to the table.
I guess it's easier for JS to deal with that if you're not using moment or something like that?
i mean you just have a single fixed number to handle then that's kinda universal
easy to put in databases, parse and such
Well, when it gets to you it's still a string on the wire, so you parse it with whatever you want into the type you want right.
i mean it's usually a number in json then
That parser (that takes in the epoch) might make less allocs, or process 2ns faster
Even if it's a number, on the wire it's still a string all the way up until it's parsed into something else.