Round date to nearest given date

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Round date to nearest given date

Post by klevis miho »

I have a list of dates.
How can I round, for example the todays date, to the nearest date on the list?
User avatar
manohoo
Forum Contributor
Posts: 201
Joined: Wed Dec 23, 2009 12:28 pm

Re: Round date to nearest given date

Post by manohoo »

1. put the dates in an array
2. cycle the array, find the difference (PHP can return result in seconds) between today and the date
3. the minimum difference is associated with the closest date

Can you code the above?

Of course, you can do the calculation in days, hrs... whatever you decide
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Round date to nearest given date

Post by klevis miho »

You are right.

But if I want to find the nearest hour date("H:i"). Let's skip the dates, just for the hours.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Round date to nearest given date

Post by pickle »

Convert them to UNIX timestamps & you can use whatever metric ( > 1 second ) you want
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply