Converting Time in UTC to Pacific time

后端 未结 3 1123
闹比i
闹比i 2021-02-07 11:17

I get a string from a external method with a time and date like so \"07/09/10 14:50\" is there any way I can convert that time in ruby to \'Pacific US\' time knowin

3条回答
  •  时光取名叫无心
    2021-02-07 11:36

    To convert from string form to a date or time object you need to use strptime

    require 'date'
    require 'time'
    
    my_time_string = "07/09/10 14:50"
    to_datetime = DateTime.strptime(my_time_string, "%m/%d/%y %H:%M")    
    
    utc_time = Time.parse(to_datetime.to_s).utc
    pacific_time = utc_time + Time.zone_offset("PDT")
    
    puts utc_time
    puts pacific_time
    

    This is pure ruby, so there are likely some rails-specific methods you could use specifically for this task, but this should get you started.

提交回复
热议问题