Skip to content

Instantly share code, notes, and snippets.

@dstagner
Last active October 10, 2024 11:50
Show Gist options
  • Save dstagner/193207fed46acf5b5bae to your computer and use it in GitHub Desktop.
Save dstagner/193207fed46acf5b5bae to your computer and use it in GitHub Desktop.
Ruby ISO8601 time in milliseconds

So you want to generate ISO8601 formatted timestamps in Ruby, but need resolution finer than a second?

First, make sure to require 'time' in order to get ISO8601 formatting. But that gets you this:

2.1.0 :001 > require 'time'
 => true 
2.1.0 :002 > Time.now.utc.iso8601
 => "2015-11-12T04:46:43Z" 

The round() method will get you finer resolution!

2.1.0 :003 > Time.now.utc.round(10).iso8601(6)
=> "2015-11-12T04:47:55.196329Z" 
@gogocurtis
Copy link

Rad

@denishaskin
Copy link

The .round(10) doesn't seem necessary (anymore?). I get the same result without it:

[12] pry(main)> Time.now.utc.round(10).iso8601(6)
=> "2017-09-27T16:46:37.095132Z"
[13] pry(main)> Time.now.utc.iso8601(6)
=> "2017-09-27T16:46:41.190868Z"
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin14]

@denishaskin
Copy link

Aha. It makes a difference if you round it to a place that shows in the output:

[1] pry(main)> Time.now.utc.round(1).iso8601(6)
=> "2017-09-27T16:59:31.500000Z"
[2] pry(main)> Time.now.utc.round(2).iso8601(6)
=> "2017-09-27T16:59:35.670000Z"
[3] pry(main)> Time.now.utc.round(3).iso8601(6)
=> "2017-09-27T16:59:39.319000Z"

@bfagundez
Copy link

Thanks!

@will-clarke
Copy link

🎉 Thanks!

@Valve
Copy link

Valve commented Mar 1, 2019

thanks!

@W-Mills
Copy link

W-Mills commented Apr 27, 2023

❤️ thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment