nanakondor
nanakondor

Reputation: 745

Create Time object with miliseconds in ruby

I want to have a Time object that can be converted into the iso8601 format: "2022-10-01T22:38:45.100Z"

I tried this:

Time.utc(2022, 10, 1, 22, 38, 45, 100).in_time_zone.iso8601(3)

but this gives me "2022-10-01T22:38:45.000Z" instead of "2022-10-01T22:38:45.100Z" the miliseconds info somehow is gone. its always 000

what am i doing wrong? thanks

Upvotes: 2

Views: 111

Answers (1)

Alex
Alex

Reputation: 29820

You're 3 zeros off:

>> Time.utc(2022, 10, 1, 22, 38, 45, 100)
=> 2022-10-01 22:38:45.0001 UTC
#                         ^
# NOTE: These are microseconds.
#       aka `usec`
>> Time.utc(2022, 10, 1, 22, 38, 45, 100).usec
=> 100

Times a 1000 to get into milisecond range:

>> Time.utc(2022, 10, 1, 22, 38, 45, 123_000).in_time_zone.iso8601(3)
=> "2022-10-01T22:38:45.123Z"

https://rubyapi.org/3.1/o/time#method-c-utc

Upvotes: 3

Related Questions