PHP Looping through dates - php

I have the following while loop which compares 2 dates to see if 1 is less than another, and if not then it adds a week to the first date.
It works fine, however where there is a greater difference between the dates (i.e. greater than 12 months) I get a timeout error as it has passed the max execution time.
Can anyone help me make this more efficient?
while($startDate->timestamp < $current_week->timestamp){
$data['weeks'][$w] = array(
'monday' => $startDate->startofWeek()->format('d/m/Y'),
'sunday' => $startDate->endofWeek()->format('d/m/Y')
);
$w++;
$startDate = $startDate->addDays(7); // Move it on to the following week
}
I should add that I'm working with the Carbon API extension for DateTime
Thanks
----Edit----
Something strange is happening that I don't understand. If I pass a date hard coded to $startDate everything after 2013-01-06 works fine (and fast) but as soon as goes after this date it times out. Any ideas anyone?

It looks like you're doing a little more to $startDate than you expect - you're modifying the object with ->startOfWeek() and ->endOfWeek() rather than just calculating the string output; my reading of the source to Carbon is that every method you call modifies the object, so the assignment in the last line of your while loop is unnecessary (it could just as easily be written as $startDate->addDays(7);. As a result of that your code is a little bit less efficient than it could be, and might even loop one or two times more than you want.
However, I would suspect this block of code isn't your real problem, and that it's further down your codebase - if your problems grow with the size of $data['weeks'] then it's probably something in the way in which you're processing it for your HTML.

Related

php datetime custom formatting

I'm trying to use
format("m/d/y \a\\t h:ia T");
to get
05/14/15 at 04:22am MDT
which used to work but now all of a sudden I'm getting
Exception: DateTime::__construct() [datetime.--construct]: Failed to parse time string (05/14/15 at 04:22am MDT) at position 9 (a): The timezone could not be found in the database in some/folders/and.files on line x
So my work around for now is taking the "at" out
format('m/d/y h:ia T');
I've found I can leave the \a in with no problem but the \a\\t causes the error. Any on how to get past this?
**edit
The timestamp being passed in is generated by mysql
2015-05-14 10:22:41
**edit
This accepted answer didn't actually solve the problem for me. I am certain the issue is unique to my server / application so once I figure it out on my own I'll post back here as to avoid any further downvotes.
I'm working with a LOT of data and a LOT of files (classes) to get this thing working so I couldn't paste all my code in here or else no one would look at this question. So here's the skinny on what was actually happening:
Inside of a loop my time value was getting replaced with the formatted value and then getting caught up in the same loop, hence why I was getting that error and everything thought I was getting time with an incorrect value because ultimately I was (the first time it was okay but not on the re-run).
resolution
When in doubt, print out the time value going INTO your DateTime->format and you may be surprised that it's not what you think it is.

Change RSS feed, but only new items

I'm fairly new to PHP, and I'm trying to write a script that solves the following
I have an RSS feed that gets saved to my server every 10 minutes (copied from elsewhere).
There is a problem with the timestamps (pubDate tag) on the RSS feed, they always have the correct date but 00:00:00 GMT as the timestamp (I have no control over this).
Therefor, when I use an autotweeting program to tweet updates from the feed (it checks it every hour or so), it won't - It only tweets the first update of each day as a result.
Therefor, what I'm trying to do to fix it to some degree is to check if the feed has changed, and if it has, change the saved pubDate to the current server time on only the new items.
I'm also kind of confused as to how I can have it check for changes - If I have a corrected version (with fairly accurate timestamps) saved to my server, it will ALWAYS think there are changes, because the timestamps will always be 00:00:00. I'm thinking, check both feeds for items including the full strings such as <guid isPermaLink="true">http://services.runescape.com/m=adventurers-log/a=161/display_player_profile.ws?searchName=A13d&id=-463827091</guid> - Since the id= at the end stays constant, it would only change the <pubDate> of items found to be new.
http://services.runescape.com/m=adventurers-log/a=161/rssfeed?searchName=A13d Here is a feed as an example. If anyone could get me started or point me to some kind of tutorial that might help, I'd really appreciate it. This is over my head, but something I need to learn how to do.
Maybe there is something wrong with your code parsing the timestamp, date format perhaps?
I believe the method of doing full string comparisons(<title> & <description>) between items with the same <guid> is your best bet. Here is some reading about RSS duplicate detection if you are interested.

Comprehensive Date Comparison PHP function

Quick embrassing question.
I have been looking for a PHP function that would calculate the difference between two timestamps and output the result based on given parameters such as
the diff in years only, diff in months only, diff in days only, etc etc
The function I made has been quite buggy and I haven't found a good one on the Net.
Please assist.
Thanks
Please take a look at DateTime::diff()
DateTime::diff — Returns the difference between two DateTime objects
You can format the output to anything you want it to be
(Provided an extra answer despite of the duplicates because they use strtotime & math and that doesn't always work out well or is a nice way to do it. Using a core function of php seems nicer to me)

HTML form input to mysql TIME

I am having an add/edit form to update and add to database, and I was not sure what the best way is to input TIME type (HH:MM:SS). Should I use multiple html text inputs for HH, MM, SS?
if so, is there a function that prepares the string for database input?
Basically what I'm trying to input is how many hours, minutes, seconds a specific task took to finish.
Can anyone point me in the right direction here?
I'm designing a website using Codeigniter (PHP).
Thanks
Let me go ahead and clarify what needs to happen a bit more...
The user is required to enter data specific to sports more in particular to a players minutes and seconds played. I'm thinking of maybe simplifying it to only minutes. Perhaps this way input is only 1 thing. Then again my question is, what method would work to convert this "minute number" to the correct MYSQL TIME format?
I wrote a helper to do something similar in an app I'm working on. Mine generates three dropdowns, hh, mm and am/pm, by calling built in form_dropdown helper. Once I get the data from the drop downs, I convert it 24hr format and then I just concatenate the strings into the right format for MySQL. Since it's a helper I can just call it from any view using form_time(). I can post it here if you think it would help to see it.
Dana
just use now() function, if your DB is
MYSQL is you want to save the current
time
e.g:
UPDATE tbl SET timemodified = NOW()
and make sure that timemodified has a
type of "time"
Ow sory miss that point. uhm maybe you need to have a start time in your DB, then after he/.she is finish his/her task. you must query on the DB the start time subtract it to the end time(your current time) then the result would be the time he/she performed the task
this checks for 2 numbers, then a ":" then 2 numbers, then a ":", then finally 2 numbers again:
$cleanTime = preg_match( '/(\d\d)\:(\d\d)\:(\d\d)/', $_POST[ 'NAME_OF_TIME_INPUT' ] );
if( !$cleanTime ){ /* ... error ... */ }
don't be scared of all the slashes, haha (I was at first when I used regexps).
replace NAME_OF_TIME_INPUT with the content of the name attribute on the <input on the <form page
i.e. if <input name="coolinput" /> then use $_POST[ 'coolinput' ]
This is one of the eternal struggles of (web) UI design, how to input time without driving the users nuts. What works for your specific case is something only you can decide, because it depends on the exact format/circumstances you need and your target audience.
As general guidelines I'd say:
Don't do a free-form text field that requires a certain format, e.g. "Enter time (HH:MM:SS)", because it's too easy to mess up and will deny the users input or mess up the time if you do no validation.
Try to avoid [0-23] [0-59] [0-59] dropdowns, since they can be quite a pain (click, scroll, click, click, scroll, click, click, scroll, click).
If ease of use is a high priority, as would be the case for public websites, maybe a Javascript enhanced timepicker is a good idea. Try not to use anything too fancy that nobody gets though (like dragging the hands on a clock).
A free-form, free-format text field might be the best idea. The user can just type in "3pm", "16:34" or "midnight". You may need to provide examples to get users started, otherwise they may feel lost. You can run this through strtotime on your end, but you may need to fill in the blanks and do a lot of validation.
Three short text fields may be a good idea if your audience is very keyboard focused and can be expected to tab through them in rapid order.
As for formatting it for SQL, however you receive the time input from the user, you should assemble it to a UNIX timestamp and format that timestamp for SQL:
date('Y-m-d H:i:s', $timestamp);
I have searched for some alternatives and solutions and I came up with this:
$min = 60;
$time[] = floor($min/60);
$time[] = $min%60;
And I used the following to convert to MySQL TIME format
INSERT INTO table (min) VALUES (MAKETIME($time[0], $time[1], 0))
I have had the same issue with working with the html time input. However, I've managed to work around it with a PHP function.
What the function does is translate the time into a format the MYSQL DATETIME datatype can understand.
Of course you will need to enter the date somehow, but I'll leave that up to you.
functions.php
function convertHtmlTime($date,$time){
$newDate = date($date);
$newTime = date($time);
$datetime = new DateTime($newDate.$newTime);
return date_format($datetime, 'YmdHis');
}
test.php
$date="2007-02-16";
$time="23:59";
echo convertHtmlTime($date,$time);
Results:
20070216235900

display time in a web page

I have page where where I list all comments for a post. Next to each comment I have a time value in full format including the date/time (2010-01-02 11:11:20).
I know that I can format it in PHP before displaying it, so it shows;
posted 40 secs ago
posted 5 days ago
but that would not be efficient as I am going to cache the page once it is generated.
On SO I see that they have some kind of java script for showing it, so it is run on the browser of the client:
alt text http://img528.imageshack.us/img528/5442/35118769.png
So basically I need a java script that runs on the browser that would instead of showing my date/time show "posted 4 hours ago". All help is welcome.
Sounds you want this: timeago: a jQuery plugin.
Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
I quote further:
Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
You can take full advantage of page caching in your web applications, because the timestamps aren't calculated on the server.
So it should fit your needs.
You can put the "timestamp" of the page into the page when you render it. This is the fixed time that doesn't change. Look at PHP's time function for this (http://www.php.net/manual/en/function.time.php). It gives you seconds since the UNIX epoch started.
Then, when the page is running, use Javascript's Date object. It encapsulates something similar. Do a getTime() on a new Javascript Date object, which will get you also seconds since the UNIX epoch.
Subtract one from the other to get the elapsed time between then and now, and do whatever pretty formatting you need to make it display right in your page.
Edit: See also Felix's answer about timeago, which is a nifty tool to do the second half of this process for you automatically.
Output your date in a format accepted by the parseDate method or as a constructor parameter for date. Place them in some nodes which can later on easily be grabbed by a javascript framework (or your own methods) and then perform some time/datediff methods on these grabbed values and replace the node's content.

Categories