简体   繁体   中英

Ruby: now.strftime(“%a, %d %b %Y %X %z”) gives wrong time

Hello guys I'm using a Ruby script to send error mails ( https://github.com/u-ichi/fluent-plugin-mail/blob/master/lib/fluent/plugin/out_mail.rb ) which relies on Net::SMTP. The time is obtained using "Time::now.strftime("%a, %d %b %Y %X %z")",

...
smtp.send_mail(<<EOS, @from, @to.split(/,/), @cc.split(/,/), @bcc.split(/,/))
   Date: #{Time::now.strftime("%a, %d %b %Y %X %z")}
   From: #{@from}
   To: #{@to}
   Cc: #{@cc}
   Bcc: #{@bcc}
   Subject: #{subject}
   Mime-Version: 1.0
   Content-Type: text/plain; charset=utf-8
   #{body}
EOS
smtp.finish

Unfortunately, I'm getting the mails with a wrong time. I don't know how Time::now.strftime works but I guess they pick the time from the server? I'm on CentOS and checked the "date" of the server and found no error...

Is there other way to get the time?

You should convert this time in a specific timezone. like:

time_zone = ActiveSupport::TimeZone.new(your_desire_time_zone)
converted_time = time.in_time_zone(time_zone)

or convert in UTC

converted_time = Time.now.utc

Then try to use strftime

converted_time.strftime("%a, %d %b %Y %X %z")

For more details, find here . Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM