Calculating how many 'Midnights' is one date past another in PHP? - php-5.2

I have a start/end times for a calculation I'm trying to do and am having a problem seeing if the end time is before 12AM the day after the start time. Also, I need to calculate how many days past the start time it is.
What I have: Start Date, End Date
What I need:
- How many 'Midnights' is the End Date past the Start Date?
Has anyone done anything like this?

This uses PHP 5.3, if you have an earlier version you may need to use unix timestamps to figure out the difference. The number of midnights should be the number of days difference assuming both start and end times have the same time. So setting both to be midnight of their current day setTime(0,0), should make the calculation correct.
Using the DateTime objects.
$start = new DateTime('2011-03-07 12:23:45');
$end = new DateTime('2011-03-08 1:23:45');
$start->setTime(0,0);
$end->setTime(0,0);
$midnights = $start->diff($end)->days;
Without using the setTime() calls, this would result in 0, because there is less than 24 hours between start and end. With the setTime() this results in 1 because now the difference is exactly 24 hours.
The diff() function was introduced in 5.3 along with the DateInterval class. In 5.2 you can still use the DateTime class but will have to work out the total days using the Unix timestamp.
$midnights = ($end->format('U') - $start->format('U')) / 86400
You can wrap that in an abs() function to the order of start/end does not matter.
Note: These functions may need to be tested for cases that involve DST.
A comment in the php date documentation uses round after dividing by 86400 (number of seconds in a day), to counter any issues that could be involved with DST.
An alternative approach with DateTimes would be to create them in the UTC.
$utcTimezone = new DateTimeZone('UTC');
$start = new DateTime('2011-03-07 12:23:45', $utcTimezone);
$end = new DateTime('2011-03-08 1:23:45', $utcTimezone);

Related

How to get N days ago in Dart's DateTime?

There's the subtract() method but the documentation says it's not aware of daylight savings which makes it pretty much useless in this case, or in any other case except where the programmer doesn't know how many milliseconds there are in 24 hours.
I'm thinking of two ways:
get the day of the month, and then subtract N from it and if it's less than 1 then subtract the month and the year if appropriate and set the day for the last day of whichever month it turns out to be
OR
subtract N days from the noon of the current day and then get start of the day for the resulting day
Is there some easier/better way to do this?
You should probably try to convert both DateTimes to UTC (standardize), then call difference(). That converts it to a nice, easy Duration, which you can convert as necessary to hours, days, months, or whatever else.
DateTime one = somedatetime.toUtc();
DateTime two = someotherdatetime.toUtc();
Duration diff = one.difference(two);
//Then just convert...
return diff.inDays;

Google spreadsheet, comparing durations

I calculated a duration between two times, e.g. between 9:00 am and 11:00 am. So far so good. Now I need to decide if this duration is less 6 hours.
I do remember that this was pain in the s in excel but nevertheless I tried it the simple way:
=IF(E2 < 06:00:00; "y"; "n")
of course that didn't work. Next:
=IF(DURATION(E2) < DURATION(06:00:00); "y"; "n")
still, it didn't work.
So, okay, how can I compare two duration?
Divide hours by 24:
=IF(E2 < 6/24, "y", "n")
Value is E2 is a formatted time, actually 1 hour is 1/24, 1 day is 1.
Some info about date and time formats here:
http://www.excel-easy.com/examples/date-time-formats.html
You can also use the HOUR function if you want to
=if(HOUR(E2)<6,ʺyesʺ,ʺnoʺ)
or
=if(E2<time(6,0,0),ʺyesʺ,ʺnoʺ)
(if you write 06:00:00 in a formula it takes it as a string not a time)
but as I'm sure someone is about to point out, the first formula above gives the wrong answer for durations of more than a day (because it takes the hour part of a datetime).
What I find interesting is that you can assume for a worksheet formula that dates and times are represented as whole numbers (days) and fractions (parts of a day) just like in Excel. If you ever have to deal with them in Google App Scripts, you suddenly find that it's object-oriented and you have no choice but to use methods like hour() to manipulate them.
I needed to use the equivalent of:
=if(TIMEVALUE(E2)<6/24, "yes", "no")

How does MongoDB compares the date only and ignores the time, such as date <= '2010-09-10'?

For some reason:
Analytic.where({:ga_date.gte => '2010-09-01'}).count() # greater than or equal to
gives back 0, but
Analytic.where({:ga_date.gte => Time.parse('2010-09-01')}).count()
gives back 230, which is the number of records (documents).
Actually, the first line on the top works in another case, so it is quite strange.
Can only the date be compared, because if it is
Analytic.where({:ga_date.lte => Time.parse('2010-09-10')}).count() # less than or equal to
then all the records with date 2010-09-10 will not be counted because Time.parse('2010-09-10') will give 2010-09-10 00:00:00, so the records will all have to be 2010-09-09 before the midnight. In other words, 2010-09-10 2am won't be included because 2am is not "less than or equal to" 00:00:00. It can be hacked by using
Analytic.where({:ga_date.lte => Time.parse('2010-09-10 23:59:59')}).count()
but it is kind of ugly. If there is a way to compare by date only like the first line of code in this post?
I think that you have two separate issues here.
Different data types
The following two lines are not equivalent. The first is a string comparison. The second is a comparison with a date object.
Analytic.where({:ga_date.gte => '2010-09-01'}).count()
Analytic.where({:ga_date.gte => Time.parse('2010-09-01')}).count()
I think you have figured this out, but it's important to be clear here. If you are storing date objects in the DB, you need to perform comparisons with date objects.
MongoDB will compare types and data.
Mismatch date storage
You are storing dates that have information for hours, minutes and seconds. However, you don't like the following notation:
:ga_date.lte => Time.parse('2010-09-10 23:59:59')
The workaround here is to use $lt and the day after.
:ga_date.lt => (Time.parse('2010-09-10') + 1.day) # or (60 * 60 * 24)
to add,
it is not strangely works, its coincidentally works when it just happens the string representation of the date happens to also lexicographically be 'greater than' the other date
other issue,
try to use only as much data fields as needed
if you meant it to be "within the calendar day",
what I usually like is to call beginning_of_day in both cases to equalize
this has the effect of neutralizing the minutes
else if you really meant within a 24h strike zone,
use ActiveSupport's '+ 1.day'

Given a date, how can I efficiently calculate the next date in a given sequence (weekly, monthly, annually)?

In my application I have a variety of date sequences, such as Weekly, Monthly and Annually. Given an arbitrary date in the past, I need to calculate the next future date in the sequence.
At the moment I'm using a sub-optimal loop. Here's a simplified example (in Ruby/Rails):
def calculate_next_date(from_date)
next_date = from_date
while next_date < Date.today
next_date += 1.week # (or 1.month)
end
next_date
end
Rather than perform a loop (which, although simple, is inefficient especially when given a date in the distant past) I'd like to do this with date arithmetic by calculating the number of weeks (or months, years) between the two dates, calculating the remainder and using these values to generate the next date.
Is this the right approach, or am I missing a particularly clever 'Ruby' way of solving this? Or should I just stick with my loop for the simplicity of it all?
Because you tagged this question as ruby-on-rails, I suppose you are using Rails.
ActiveSupport introduces the calculation module which provides an helpful #advance method.
date = Date.today
date.advance(:weeks => 1)
date.advance(:days => 7)
# => next week
I have used the recurrence gem in the past for this purpose. There are a few other gems that model recurring events listed here.
If you are using a Time object, you can use Time.to_a to break the time into an array (with fields representing the hour, day, month, etc), adjust the appropriate field, and pass the array back to Time.local or Time.utc to build a new Time object.
If you are using the Date class, date +/- n will give you a date n days later/earlier, and date >>/<< n will give you a date n months later/earlier.
You can use the more generic Date.step instead of your loop. For example,
from_date.step(Date.today, interval) {|d|
# Each iteration of this block will be passed a value for 'd'
# that is 'interval' days after the previous 'd'.
}
where interval is a length of time in days.
If all you are doing is calculating elapsed time, then there is probably a better approach to this. If your date is stored as a Date object, doing date - Date.today will give you the number of days between that date and now. To calculate months, years, etc, you can use something like this:
# Parameter 'old_date' must be a Date object
def months_since(old_date)
(Date.today.month + (12 * Date.today.year)) - (old_date.month + (12 * old_date.year))
end
def years_since(old_date)
Date.today.year - old_date.year
end
def days_since(old_date)
Date.today - old_date
end

Rails: find by day of week with timestamp

I need to grab the records for same day of the week for the preceeding X days of the week. There must be a better way to do it than this:
Transaction.find_by_sql "select * from transactions where EXTRACT(DOW from date) = 1 and organisation_id = 4 order by date desc limit 7"
It gets me what I need but is Postgres specific and not very "Rails-y". Date is a timestamp.
Anyone got suggestions?
How many days do you want to go back?
I have written a gem called by_star that has a dynamic finder suited for finding up to a certain number of days in the past. If the number of days was always a number you could use this finder:
Transaction.as_of_3_days_ago
If it was dynamic then I would recommend using something such as future or between, depending on if you have transactions in the future (i.e. time travel):
Transaction.future(params[:start_date].to_time)
Transaction.between(params[:start_date].to_time, Time.now)
AFAIK Rails has no any methods to do this by other way. So best, and faster, solution - build DOW index on date column and use your query.

Resources