Вопрос

I am having a hard time wrapping my head around this problem...

I am running an app with voting, and rather than having a new idea last for just 24 hours from the created_at date, I want the voting to start at the "next noon" and last for 24 hours.

i.e. if you created an idea at 8:00pm on a wednesday, people could vote on the idea until noon on Friday (24 hours after the next noon). Or if you created an idea at 11:50am on thursday, you would also have until noon on Friday to vote.

So basically I just need to find a way to make an instance... say:

     @recentideas = current.user.ideas.where(:created_at => (nextnoontime)...(nextnoontime + 24.hours))

I acknowledge that the above is not actual code, but just to put it into perspective...

Thanks in advance.

Update with soultion:

It turns out the easier solution (not exactly elegant) was to say:

     <% if idea.created_at.hour < 12 %>
       <% @nextnoon = idea.created_at.midnight + 12.hours %>
       <% @timedif = @nextnoon - idea.created_at %>
     <% else %> 
       <% @nextnoon = idea.created_at.tomorrow.midnight + 12.hours %>
       <% @timedif = ((@nextnoon - 12.hours) - idea.created_at) + 12.hours %>
     <%end%>

And then the related if statement was:

     <% if idea.created_at > ((24.hours + @timedif)/3600).hours.ago %>

A bit clunky, but I'll clean it up at a later date.

Это было полезно?

Решение

You can find noon of the ending day like so

now = DateTime.now
twelve_hours_from_now = now + 12.hours
beginning_of_day = DateTime.new(twelve_hours_from_now.year, twelve_hours_from_now.month, twelve_hours_from_now.day)
noon_of_ending_day = beginning_of_day + 36.hours

So your query would be

@recentideas = current.user.ideas.where(:created_at => (now...noon_of_ending_day))

although that query doesn't make too much sense as no ideas will have been created between now and some time in the future. We are still waiting for those ideas to appear.

Другие советы

I had a similar issue and this is what I used:

1. DateTime.tomorrow +12.hours
2. DateTime.tomorrow + 1.day + 12.hours

Here's a clean way to find the next "noon".

# Today
time = DateTime.now

# Noon, today
time += (12 - time.hour).hours
time -= time.min.minutes
time -= time.sec.seconds

# Noon tomorrow, if noon today is in the past
time += 1.day unless time.future?

Or use chronic:

time = Chronic.parse "noon tomorrow"
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top