Ran into this issue in Crystal 0.19.1:
it "- computes correct span across different kinds" do
local_now = Time.now
utc_now = Time.now.to_utc
utc_now.should be_close(local_now, Time::Span.new(0, 0, 1))
end
I'd expect this test to pass. However, the difference between utc_now and local_now comes to 07:00:00.0000010 for me (I'm in PDT, currently UTC-7). As a result, this test fails:
1) Time - computes correct span across different kinds
Failure/Error: utc_now.should be_close(local_now, Time::Span.new(0, 0, 1))
expected 2016-09-14 15:26:23 UTC to be within 00:00:01 of 2016-09-14 08:26:23 -0700
# ./spec/std/time/time_spec.cr:626
I'm happy to work on this and open a PR later this week, but have two questions:
Time::Kind only appears to have three options; how could I reliably write this test (specify a specific timezone) so people where UTC == local time can still run this test as intended?Time::AbsoluteSpan that will represent a span between two points in time regardless of timezone?Hmm... so you expect local time vs. UTC time to be one hour apart in every place on the Earth?
No, my intent is that they represent the same point in time, so the delta should be minimal. Time.now should be the "same" point in time, even if I get a new Time instance in a different timezone.
I thought the three-int constructor was HMS — expect them to be within 1s. Might've read the API wrong though …
My original "real-world" use case:
it "fills in the created_at field with a recent timestamp" do
now = Time.now
user = Register.new.create_user("[email protected]", "password")
fetched_user = User.get(user.id.as(Int32))
fetched_user.created_at.not_null!.should be_close(now, Time::Span.new(0, 0, 1))
end
Where the database will automatically use UTC times for all returned result, regardless of the original Time instance's timezone
Oh, I see. I think Time#- doesn't take into account the kind of the times, this is probably a bug. In any case, Time will most surely change, I don't like the current design and all the different kind times. This was inspired by C#/Mono, but their Time doesn't support nanoseconds and dealing with kinds is a mess. Probably each time should have a location/time-offset. So instead of fixing this it's probably better to redesign this at some point.
For now the best thing to do would be to always do operation on UTC times.
(though maybe this can be fixed easily so in the meantime it's still useful, I'll try)
@feifanzhou I think it's fixed now.
By the way, nice use of be_close, I never though of using it with times, only with floats :-)
@asterite you, sir, are unbelievably fast :)
Chose to use be_close because technically the two times aren't identical, so it felt a bit wrong saying the difference should "equal" 0
Most helpful comment
@feifanzhou I think it's fixed now.
By the way, nice use of
be_close, I never though of using it with times, only with floats :-)