2012-02-23 78 views
1

我是Ruby的新手,我试图在早上9点到上午11点之间返回电子邮件的数量。使用Ruby IMAP在两个日期之间搜索

例如。

@received_today = imap.search(["SINCE", @today.strftime("%d-%b-%Y-%H"):"BEFORE", @today.strftime("%d-%b-%Y-%H")]).count.to_s 

我知道这是错误的,但这是我最接近的猜测如何做到这一点。任何帮助将不胜感激。

回答

2

也许是这样的:

require 'date' 
start_time = Net::IMAP.format_datetime(DateTime.strptime("09:00", "%H:%M")) 
end_time = Net::IMAP.format_datetime(DateTime.strptime("11:00", "%H:%M")) 
@received_today = imap.search(["SINCE", start_time, "BEFORE", end_time ]).count 

UPDATE: 尝试#2 :)

由于IMAP SEARCH命令忽略自从和前条件的部分时间这应该工作:

require 'date' 

today = Net::IMAP.format_date(Date.today) 

start_time = DateTime.strptime("09:00", "%H:%M") 
end_time = DateTime.strptime("11:00", "%H:%M") 

@received_today = imap.search(["ON", today]) # get sequence nums of todays emails 

# fetch the INTERNALDATE-s and count the ones in the timeframe 
count = imap.fetch(@received_today, "INTERNALDATE").count{ |data| 
    time = DateTime.parse(data.attr["INTERNALDATE"]) 
    time.between? start_time, end_time 
} 
+0

谢谢 - 我会检查并接受它是否有效。我也在考虑只进行一次搜索,使用%H返回当天1小时的所有电子邮件,然后对其进行迭代。 – krapdagn 2012-02-23 20:24:49