php date/time intervals with subscription - php

I need some help wrapping my head around this. I am trying to develop something that does monthly, weekly, quarterly, yearly subscriptions. I need to figure out when the next charge date is. But I'm getting confused getting through the logic. I can easily calculate when a year is from the original transaction (<? echo date("Y-m-d",strtotime($charge_interval, strtotime($original_charge_time))); ?>), where $charge_interval is '+3 months' or '+1 month', etc. But.. if 3 months have passed, I can't just use that equation, because it will show the "next" date as one month from the original. Any advice?
EDIT: more precision. My data is stored in a DB, and I need to ensure its getting the "next" month rather than a month from original date. Say transaction took place Nov 15th. Its now July 6th. I want "next transaction" to say July 15th, NOT Dec 15th (which is what the above code would accomplish), and to say "we have already have 7 charges before".

strtotime is little-know, but can show itself to be very useful for this kind of use.
EDIT: here may be a clue:
$charges = 0;
$now = time();
$next_charge_time = strtotime($original_charge_time);
while ($next_charge_time < $now)
{
$charges++;
$next_charge_time = strtotime($charge_interval, $next_charge_time);
}
$next_charge_time = date("m/d/Y", $next_charge_time);
echo "You have been charged $charges times since $original_charge_time.";
echo "<br/>";
echo "Next charge will be on $next_charge_time";

Doesn't php have a dateadd function of some kind to add a number of months to a date?
Like this one?
http://php.net/manual/en/function.date-add.php

Use DateTime() with http://us3.php.net/manual/en/datetime.add.php

Try mktime(0, 0, 0, strftime("%d", $origtime), date("m")+1, date("Y"));
that would mean midnight of course (first three parms are H, M, S, you could use strftime for those too if you want)
that would work for the next calendar month, you could just remove the "+1" for the same month if you work out the day falls later than the current day.

Related

Change url of file_get_contents based on time

$string = file_get_contents("http://domain.com/api/data?after=1412640000");
My PHP code displays the json data based on the epoch time. This time is always at 00:00:00 UTC. I need the time in the url to change at different time frames like 1 day when it is available.
I can put a variable in the url to get the current time but Im lost on the setting it to 00:00:00 UTC for when the new day would roll over.
Ive searched and I keeping getting partial results but not quite what I need. First time posting here. Thanks for the help.
Edit: I got this to work for daily changes but I need two other time frames like one week and a month.
Heres the code:
$daily = gmdate(strtotime('yesterday'));
$string = file_get_contents("http://domain.com/api/data?after={$daily}");
The gmdate is what did the trick for UTC. Now for a week time frame. An example would be displaying the date of the 2nd of the month until the week rolls over then it displays the new weekly date from the 9th.
strtotime is more powerful than you think, just the naive way works:
strtotime("-1 week")
strtotime("-1 month")
Ok so finally figured it out. Here is the code to enter epoch from certain date time intervals of daily, weekly and monthly all in UTC.
$daily = gmdate(strtotime('yesterday'));
$string = file_get_contents("http://domain.com/api/data?after={$daily}");
$weekly = mktime(23, 59, 59, date('n'), date('j'), date('Y')) - ((date('N'))*3600*24);
$string = file_get_contents("http://domain.com/api/data?after={$weekly}");
$monthly = mktime(0, 0, 0, date('m'), 1, date('Y'));
$string = file_get_contents("http://domain.com/api/data?after={$monthly}");
$daily is the simplest and easiest. $weekly will start with Mondays and will give that time until the next Monday comes around and thats also how $monthly works but with on the 1st.

Understanding date processing with strtotime

I'm trying to get my head round someone else's code which they've written for handling the dates of when news stories are published. The problem has come up because they are using this line -
$date = strtotime("midnight", strtotime($dateString));
to process a date selected using a jquery calendar widget. This works fine for future dates, but when you try to use a date which is in the previous calendar year, it uses the current year instead. I think this is due to "midnight" finding the closest instance of the selected day and month.
I could remove the "midnight", but I'm not sure what the repercussions of this would be - is there a reason that the midnight could be there?
EDIT: this is the full block of code which handles the date. The date contains the time, which allows the user to publish an item at a specific time.
$array['display_date'] = '24 October, 2011 17:30';
$string = $array['display_date'];
$dateString = substr($string, 0, -5);
$timeArray = explode(':', substr($string, -5));
$hours_in_secs = 60 * 60 * $timeArray[0];
$mins_in_secs = $timeArray[1];
$date = strtotime("midnight", strtotime($dateString));
$timestamp = $date + $hours_in_secs + $mins_in_secs;
//assign timestamp to validation array
$array['display_date'] = $timestamp;
echo $array['display_date']; // Output = 1351094430 (Oct 24 2012 17:00:30)
This really depends on what $dateString contains. Assuming your jQuery widget delivered the time portion as well, your colleague likely wanted to remove the time portion. Compare the following:
echo date(DATE_ATOM, strtotime('2010-10-01 17:32:00'));
// 2010-10-01T17:32:00+02:00
echo date(DATE_ATOM, strtotime("midnight", strtotime('2010-10-01 17:32:00')));
// 2010-10-01T00:00:00+02:00
If your widget doesnt return the time portion, I dont see any reason for setting the date to midnight, because it will be midnight automatically:
echo date(DATE_ATOM, strtotime('2010-10-01'));
// 2010-10-01T00:00:00+02:00
Note that all these are dates in the past and they will result in the given year in the past, not the current year like you say. If they do in your code, the cause must be somewhere else.
Will there be repercussions when you change the code? We cannot know. This is just one line of code and we have no idea of any context. Your unit-tests should tell you when something breaks when you change code.
EDIT after update
The codeblock you show makes no sense whatsoever. Ask the guy who wrote it what it is supposed to do. Not only will it falsely return the current year for past years, but it will also give incorrect results for the minutes, e.g.
24 March, 2010 17:30 will be 2012-03-24T17:00:30+01:00
I assume this was an attempt at turning 24 March, 2010 17:30 into a valid timestamp, which is in a format strtotime does not recognize. But the approach is broken. When you are on PHP5.3 use
$dt = DateTime::createFromFormat('d F, Y H:i', '24 March, 2010 17:30');
echo $dt->format(DATE_ATOM); // 2010-03-24T17:30:00+01:00
If you are not on 5.3 yet, go through https://stackoverflow.com/search?q=createFromFormat+php for alternate solutions. There is a couple in there.

Month by week of the year?

I'm trying to get the number of the month of the year by the number of a week of the year and the year.
So for example week 1 is in january and returns 1, week 6 is in february so I want 2.
I tried to go with date_parse_from_format('W/Y') but had no success (it's giving me errors).
Is there any way to go with date_parse_from_format() or is there another way?
print date("m",strtotime("2011-W6-1"));
(noting that in 2011, January has six weeks so week 6 (by some definitions) is in month 1).
Just wanted to add a note for the first answer, the week number should be 01-09 for Weeks 1 through 9 (it will always give month 1 if you don't add the leading zero)
date("m",strtotime("2011-W06-1"));
Using PHP DateTime objects (which is the preferred way of dealing with dates see links below for more info) you can accomplish it this way:
$dateTime = new \DateTime();
$dateTime->setISODate($year,$week);
$month = $dateTime->format('n');
Note that the following will not work as week "W" is not a supported format:
$month = \DateTime::createFromFormat("W/Y ", "1/2015")->format('n');
The format used by this method is the same supported by the function you where trying to use date_parse_from_format, hence the errors.
Why PHP DateTime Rocks
DateTime class vs. native PHP date-functions
strtotime notes
PHP/Architect's Guide to Date and Time Programming (Chapter 2)
Something like this will do, this is also tested and works:
function getMonthByNumber($number,$year)
{
return date("F",strtotime('+ '.$number.' weeks', mktime(0,0,0,1,1,$year,-1)));
}
echo getMonthByNumber(27,2011);
Hope this helps

Get Last Monday - Sunday's dates: Is there a better way?

I'm preparing a query for mySQL to grab record from the previous week, but I have to treat weeks as Monday - Sunday. I had originally done this:
WHERE YEARWEEK(contactDate) = YEARWEEK(DATE_SUB(CURDATE(),INTERVAL 7 DAY))
to discover that mySQL treats weeks as Sunday - Monday. So instead I'm parsing getting the begin & end dates in php like this:
$i = 0;
while(date('D',mktime(0,0,0,date('m'), date('d')-$i, date('y'))) != "Mon") {
$i++;
}
$start_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+7), date('y')));
$end_date = date('Y-n-j', mktime(0,0,0,date('m'), date('d')-($i+1), date('y')));
This works - it gets the current week's date for monday (walking backwards until a monday is hit) then calculates the previous week's dates based on that date.
My question is: Is there a better way to do this? Just seems sloppy, and I expect someone out there can give me a cleaner way to do it - or perhaps not because I need Monday - Sunday weeks.
Edit
Apparently, there is:
$start = date('Y-m-d',strtotime('last monday -7 days'));
$end = date('Y-m-d',strtotime('last monday -1 days'));
That's about a million times more readable. Thank you.
you can use strtotime for this kind of date issues
echo strtotime("last Monday");
(complementing on marvin and Stomped ) Also you can use it this way
echo date('Y-m-d',strtotime('-1 Monday')); //last Monday
echo date('Y-m-d',strtotime('-2 Monday')); //two Mondays ago
echo date('Y-m-d',strtotime('+1 Monday')); //next Monday
strtotime("previous week Monday")
Monday of the previous week.
Marvin's answer is really elegant, although if you really wanted to go for performance you could do it with a little arithmetic. You could derive a formula/method to convert an arbitrary date to "days since some starting point" (probably 01.01.0000) and then the rest of the operations would be easy with that. Getting the day of week from such a number is as simple as subtracting and getting the remainder of a division.
Actually, PHP had a Date class in its PEAR library which did exactly this.
I have to point out for all the readers here there is a big issue with marvin's answer
Here is the catch
The "last Monday" function will return date the "latest" Monday.It will be explained like this , if today is Monday, then it will return the date of "LAST WEEK" Monday, however if today is not Monday, it will return "THIS WEEK" Monday
The Question is request to return "Last Week" Monday. Therefore the result will be incorrect if today is not Monday.
I have solved the issue and wrapped in my Date Time Helper
It will be only one line after you "INCLUDE" the class
$lastWeekMonday = Model_DTHpr::getLastWeekMonday();
Check Here
https://github.com/normandqq/Date-Time-Helper

work out the date of the fourth saturday in the current month

Bit stuck about how to go about this one. Given the current month, I need to to return the date of the fourth saturday of each month.
e.g. This month would be Feb 20th, next would be March 27th.
Thanks
I'm not a PHP coder, however, it seems strtotime is what you're after.
You can use strtotime("fourth Saturday") and it will return the 4th saturday.
Check out the strtotime docs.
EDIT:
Just to make the answer complete, thanks to Tom and Paul Dixon
date('dS F',strtotime('Fourth Saturday '.date('F o')));
You can use strtotime to find "next saturday" based on a starting date. If that starting date is the day before the earliest possible preceding day (21st) we get the answer...
//required year/month
$yyyymm="2009-01";
//find next saturday after earliest possible date
$t=strtotime("next saturday", strtotime("{$yyyymm}-21"));
//here you go!
echo "4th saturday of $yyyymm is ".strftime("%Y-%m-%d",$t)."\n";
Earliest possible 4th repeat of a day in any month is the 22nd (1,8,15,22), last possible 4th repeat is 28th (7,14,21,28).
EDIT: Although it's not clear in the documentation, you can request the "fourth saturday" too - use the zeroth day of the month as the basis:
$t=strtotime("fourth saturday", strtotime("{$yyyymm}-00"));
or omit the basis time and specify the month and year directly:
$t=strtotime("fourth saturday feb 2009");
Tip of the hat to Robin "I'm not a PHP coder" Day for spotting that :)
The earliest date for the fourth Saturday is the 22nd of the month. So look at the 22nd, see what day of the week it is, if it's not Saturday, add one day to the date, and check again, until you find a match (maximum you would have to check is 6 days).
Find the first Saturday of the month, and then add three weeks to that.
If you don't know when the first Saturday is (or, rather, don't know specifically a date corresponding with a day name), you might want to look at the Doomsday algorithm, which I conveniently looked at for another post with a somewhat similar issue.
function fourth_saturday($year, $month)
{
$info = localtime(mktime(0, 0, 0, $month , 1, $year));
return 28 - $info[6];
}
in PHP rather than pseudo code (think requires 5.2)
$date = getdate();
$date-> setDate($date->format('Y'), $date->format('Y'), '1'); // 1st of month.
while ($date->format('w' != 6)
$date->modify("+1 day");
$date->modify("+21 day"); // date is now on the fourth saturday

Categories