4

This is the time format I want to convert

time = Time.parse('2020-07-02 03:59:59.999 UTC')
#=> 2020-07-02 03:59:59 UTC

I want to convert to string in this format.

"2020-07-02T03:59:59.999Z"

I have tried.

time.strftime("%Y-%m-%dT%H:%M:%S.999Z")

Is this correct? Any better way?

0

3 Answers 3

6

You can just use Time#iso8601 with the desired number of fraction digits as an argument:

time = Time.current.end_of_hour

time.iso8601(3) #=> "2020-07-01T10:59:59.999Z"
1
  • That's what I wanted to know. Thank you!
    – user13758797
    Commented Jul 1, 2020 at 11:09
1

If you want to handle the output format explicitly via strftime, there are some things to keep in mind:

Instead of hard-coding 999, you should use %L to get the actual milliseconds:

time = Time.parse('2020-07-02 03:59:59.999 UTC')
#=> 2020-07-02 03:59:59 UTC

time.strftime('%Y-%m-%dT%H:%M:%S.%LZ')
#=> "2020-07-02T03:59:59.999Z"

Use combinations for common formats, e.g. %F for %Y-%m-%d and %T for %H:%M:%S:

time.strftime('%FT%T.%LZ')
#=> "2020-07-02T03:59:59.999Z"

If you are dealing with time zones other than UTC (maybe your machine's local time zone), make sure to convert your time instance to utc first:

time = Time.parse('2020-07-02 05:59:59.999+02:00')
#=> 2020-07-02 05:59:59 +0200

time.utc
#=> 2020-07-02 03:59:59 UTC

time.strftime('%FT%T.%LZ')
#=> "2020-07-02T03:59:59.999Z"

or to use %z / %:z to append the actual time zone offset:

time = Time.parse('2020-07-02 05:59:59.999+02:00')

time.strftime('%FT%T.%L%:z')
#=> "2020-07-02T05:59:59.999+02:00"
0

For APIs you should use utc.iso8601:

> timestamp = Time.now.utc.iso8601
=> "2015-07-04T21:53:23Z"

See: https://thoughtbot.com/blog/its-about-time-zones#working-with-apis