Home > Software engineering >  Create Time object with miliseconds in ruby
Create Time object with miliseconds in ruby

Time:09-20

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

CodePudding user response:

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

  • Related