首页 > 解决方案 > 如何在rails中将日期时间字符串转换为utc?

问题描述

我有日期格式Sat, 01 Jan 2000 16:20:00 UTC +00:00 我刚刚将给定表格的日期时间值取为“2000-01-01 16:20:00”,从这里我刚刚花费时间 16:20:00 strftime('%H:%M:%S')现在我需要将其转换为 UTC 这是 m 尝试更新的 rake 文件,主要问题是暂存环境的时间转换。

bookings = Booking.where(booking_status: 'booked')
                  .where('booking_date = ?', Date.current)
if bookings.present?
  bookings.each do |booking|
    date = booking&.booking_time&.strftime('%H:%M:%S')&.to_time&.utc

    booking.update(booking_status: 'no_show') if date < Time.current
  end
end

标签: ruby-on-railsruby

解决方案


首先,我同意上面的评论,好像你真的不需要那个额外的列,而不是你可以在模型中定义一个函数,在需要时返回值:

def book_status
   date = booking_time&.strftime('%H:%M:%S')&.to_time&.utc
   date < Time.current ? 'no_show' : 'booked'
end

然后对于您的图书模型的任何实例,您可以像这样访问他的状态my_book.book_status

但是如果你真的需要/想要那个额外的列,有一种方法可以加快这个过程,你在代码中遇到的问题是你执行n 个SQL 查询来更新每个项目加上如果你使用更新函数,你也会触发所有每个 book 实例的 ActiveRecord 回调,一个可能的解决方法是使用update_all,但要考虑到如果你需要回调,那么你需要保持它的方式,无论如何,这就是如何做到这一点update_all(应该加快进程):

books_ids = Booking.where(booking_status: 'booked').
                  where('booking_date = ?', Date.current).
                  select { |book_i| book_i.booking_time&.strftime('%H:%M:%S')&.to_time&.utc < Time.current }.map(&:id)

Book.where(id: books_ids).update_all(booking_status: 'no_show')

上面的代码将生成 2 个查询而不是n个查询来获取您想要更新的 books_ids,第二个查询来真正更新这些图书(没有触发回调),无论如何,我推荐第一种方法而不是这种方法。

第三种选择是根据需要进行如下操作:

def book_status
   date = booking_time&.strftime('%H:%M:%S')&.to_time&.utc
   if date < Time.current
     self.update(booking_status: 'no_show')
     booking_status
   else
     booking_status
   end
end

如果您不想要/不需要回调,请改用update_column

编辑:

如果您想要解析格式,您可以这样做:

require 'time'
p Time.parse('16:20:00').utc

您可以在此处测试上述代码段。


推荐阅读