Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Convert time to string

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?


2 Answers

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"
like image 170
spickermann Avatar answered Oct 16 '25 19:10

spickermann


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"
like image 44
Stefan Avatar answered Oct 16 '25 19:10

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!