Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Time to String in User Time Zone in Ruby

I've got a time with value Wed, 23 Mar 2016 00:07:00 ICT +07:00, and when calling to_s, it returns me "03/23/2016 12:07 AM", but what I need is "03/23/2016 07:07 AM".

Appreciate an answer with explanation.

like image 349
Vibol Avatar asked Sep 14 '26 12:09

Vibol


2 Answers

If you ever need a time in a specific format, you should reach for strftime. The format string you want is '%m/%d/%Y %H:%M %p', the manual I linked to above explains what all the format specifiers mean. Anything that is time-ish in Ruby or Rails is going to have a strftime method that matches Time#strftime so it doesn't matter if you have a Time, DateTime, ActiveSupport::TimeWithZone, ...

You also appear to want to convert the time to UTC but there's a method for that too: utc.

Putting those together:

t.utc.strftime('%m/%d/%Y %H:%M %p')

You really shouldn't use to_s or inspect on times for anything other than debugging. You're better off going straight to strftime so that you will get exactly the format you're after.

like image 73
mu is too short Avatar answered Sep 17 '26 03:09

mu is too short


I guess this would work:

(t + (7*60*60)).to_s where t is an instance of Time.

like image 27
Sagar Pandya Avatar answered Sep 17 '26 04:09

Sagar Pandya



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!