Change url of file_get_contents based on time - php

$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.

Related

How to get the starting weekday of a month in a future year using date() in php

I am using a date() format to return the starting weekday of a month. The code I have below is how I am attempting to achieve this. For the current year (2018) this works as normal. For example This month is august and the starting weekday is a Wednesday so it will return a 3 for Wednesday. (It works so far)
As we advance the year to 2019 it starts to get the starting weekday wrong.
For example January 2019 starts on a Tuesday so it should return 2 but returns 1. (one day out)
This error seems to be cumulative so if we go to 2020 then it is 2 days out etc.
I have tried so hard to format this Date() correctly but to no avail. Is this even the correct way to do this?
Code:
$future_month = 5 /*for January 2019*/
$starting_weekday = date('N',mktime(0, 0, 0, date('m', strtotime('+'.$future_month.' months', strtotime(date('Y-m-01')))), 1));
Many Thanks
Cameron
Your code makes this much more complicated than it needs to be.
$dt = new DateTime('first day of +5 months')
$dt->format('N'); // "2"

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.

php date offset

This is my issue, i have a time stamp coming from php, the servers time is 3 hours off from mine. I have offset the time by three hours but quickly realized that at 2 am the date part of the time stamp reads the day before date (day and month) and that does not change till 3 am. This is an issue because the date is important and i need it to be accurate. I have tried the timezone change but cant seem to get it to work. I live in ohio so thats the time i need and the timezone the server is in is three hours behind. So one of two things can help me, a timezone change that works or offsetting the day by 3h, not only the time. Here is my current code:
$timechange = mktime(date("g")+3, date("i"), 0, date("m"), date("d"), date("y"));
$date = date("D, d M Y g:i",$timechange);
$now = new DateTime('now', new DateTimeZone('America/Ohio')); // whatever your TZ's name happens to be
$now->setTimeZone('America/ServerTZ'); // reset to your server's TZ
$datestr = $now->format('D, d M Y g:i'); // get TZ's time as a nice string
By doing the setTimeZone, you affect the OUTPUT of the function - internally the timestamp is unchanged.
Instead of adjusting the times yourself, try just setting the timezone beforehand.
See http://php.net/manual/en/function.date-default-timezone-set.php

php date/time intervals with subscription

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.

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

Categories