today and not last 24 hours? - php

i my php codes i do time()-86400 to fetch everything from the last 24 hours, but how i can get everything today or everything from yesterday. thus it is no longer 86400 seconds, it should be after 12 midnight till current time.
hope this makes sense.. but how i can do this?

If you are "fetching" from a database, why not do it in the query?
SELECT * FROM `table` WHERE DATE(`created_at`) = '2011-03-28';
If you are storing the date as a unix timestamp:
SELECT * FROM `table` WHERE DATE(FROM_UNIXTIME(`created_at`)) = '2011-03-28';

time()-strtotime('today') - difference between now and midnight; time()-strtotime('yesterday') - difference between now and yesterday midnight; time()-strtotime('-2 days')...
for yesterday only (range $min to $max)
$start = strtotime('yesterday')
$end = strtotime('today') - 1;
etc.

Following will give you the seconds passed since January 1, 1970. Every object with a timestamp higher than this value is from the current day (given that you have set your timezones and local time correctly).
$time = strtotime(date('Y-m-d 00:00:00'));

You can use the PHP date and strtotime function in order to pick a day from now and retrieve the seconds that specific date. For more info, see: http://php.net/manual/en/function.date.php and http://php.net/manual/en/function.strtotime.php

I agree with Gordon here - there are so many date/time examples. But hey, let's go over it again - assuming today begins at midnight, you use:
$start = strtotime('today');
Assuming "today" ends at 23:59, simple arithmetics imply that if you increment the $start by 24 hours and take away 1 second - you'll reach the end of today.
So:
$start = strtotime('today');
$end = $start + (3600 * 24) - 1;

Related

PHP - Exclude all non-business hours / days from time difference

I have a table which shows the time since a job was raised.
// These are unix epoch times...
$raised = 1360947684;
$now = 1361192598;
$difference = 244914;
$difference needs to exclude any time outside of business hours (ex, 9-5 and weekends).
How could I tackle this?
The thing you have to do are 3 in numbers.
You take your start date and calculate the rest time on this day (if it is a business day)
You take your end date and calulate the time on this day and
you take the days in between and multiply them with your business hours (just those, that are business days)
And with that you are done.
Find a little class attached, which does those things. Be aware that there is no error handling, time zone settings, daylight saving time, ...
input:
start date
end date
output:
difference time in seconds
adjustable constants:
Business hours
Days that are not business days
Very bad idea, but I had no choice because I'm on php 5.2
<?php
date_default_timezone_set('Asia/Seoul');
$start = 1611564957;
$end = 1611670000;
$res = 0;
for($i = $start; $i<$end; $i++){
$h = date("H", $i);
if($h >= 9 && $h < 18){
//echo date("Y-m-d H:i:s", $i) . "<br>";
$res = $res + 1;
}
}
echo $res;
Use DateTime.
Using UNIX time for this is slightly absurd, and you would have to literally remake DateTime.
Look up relative formats where you can specify the hour on the day, e.g.
$date = new DateTime($raised);
$business_start = new DateTime("09:00"); // 9am today
$business_end = new DateTime("17:00"); // 5pm today
The rest is for you to work out.
Oh, and instead of start/end, you could probably use DateInterval with a value of P8H ("period 8 hours")
The problem with using timestamps directly is that you are assigning a context to a counter of seconds. You have to work backwards from the times you want to exclude and work out their timestamps beforehand. You might want to try redesigning your storage of when a job is raised. Maybe set an expiry time for it instead?

caculating dates with php

I have a general question on calculating dates with php.
What happens if I store a timestamp like this in my database:
$db_timestamp = '2010-01-31 00:00:00';
and then run a daily script that checks if a month has passed since the timestamp was saved in the database:
if ($db_timestamp == make_unix_timestamp(mktime(0, 0, 0, date("m") - 1, date("d"), date("Y")), TRUE, 'eu')))
{
do something
};
my problem is that i just realized that this wouldn't work for all dates. in this case 'do something' would not be called in February, since February doesn't have a 31st day. any idea on how to implement something like that?
First, your DBMS should have a data type for date/time. They all store timestamps in a similar way.
MySQL then provides a function called UNIX_TIMESTAMP() if you need to return a timestamp PHP can understand.
SELECT UNIX_TIMESTAMP(`createTime`) FROM `articles`;
The opposite function is called FROM_UNIXTIME():
INSERT INTO `articles` (`createTime`) VALUES ( FROM_UNIXTIME(12345678) );
MySQL (or another DBMS for that matter, but I'm using MySQL as an example) has a slew of other functions to calculate time differences. For example, to know if an article is more than one month old, use can use DATE_SUB():
SELECT * FROM `articles`
WHERE `article`.`createTime` <= DATE_SUB(NOW(), INTERVAL 1 MONTH);
(In MySQL5 and above, you can also write it as such)
SELECT * FROM `articles`
WHERE `article`.`createTime` <= (NOW() - INTERVAL 1 MONTH);
$ts = strtotime($db_timestamp);
if ($ts < (time() - 2592000))
{
do something;
}
2592000 seconds = 30 days
You could use date_diff http://us3.php.net/manual/en/datetime.diff.php
or do a comparison of the timestamp in your database with
strtotime("-1 month");
You could check the timestamp using a query:
MySQL:
select date from table where date < now() - INTERVAL 1 MONTH;
It kind of depends on how you consider "one month".
If "one month" means "30 days", a solution would be to compare the timestamp you get from the database with the current timestamp :
$db_timestamp = strtotime('2010-01-31');
$current_timestamp = time();
var_dump( ($current_timestamp - $db_timestamp) / (24*3600) );
If the difference is 30 days... that's it.
A couple of notes :
strtotime converts a date to an UNIX timestamp-- i.e. the number of seconds since 1970-01-01
time returns the current UNIX timestamp
you can compare timestamps : they only represent a number of seconds ; and there are 24*60*60 seconds per day ;-)

How to obtain, increment, and compare datetime in PHP?

I am developing a quiz site and there is time for x min to answer the quiz. So when user clicks on start quiz link the starttime (current time at this instant) is recored in session. Also the endtime (start_time+ 30 min) is recorded in session and every time he submits a answer the current time is compared with the quiz end time. Only if the current time is less than end_time the answer should be accepted.
How can I get the currentdatetime?
How can I add x minutes to current this datetime?
How can I compare (<=) datetime ?
I think we should use date time. Is it right?
PHP measures time as seconds since Unix epoch (1st January 1970). This makes it really easy to work with, since everything just a single number.
To get the current time, use: time()
For basic maths like adding 30 minutes, just convert your interval into seconds and add:
time() + 30 * 60 // (30 * 60 ==> 30 minutes)
And since they're just numbers, just do regular old integer comparison:
$oldTime = $_SESSION['startTime'];
$now = time();
if ($now < $oldTime + 30 * 60) {
//expired
}
If you need to do more complicated things like finding the date of "next tuesday" or something, look at strtotime(), but you shouldn't need it in this case.
use php builtin functions to get time:
<?php
$currentTimeStamp = time(); // number of seconds since 1970, returns Integer value
$dateStringForASpecificSecond = date('Y-m-d H:i:s', $currentTimeStamp);
?>
for your application that needs to compare those times, using the timestamp is more appropriate.
<?php
$start = time();
$end = $start + (30 * 60); // 30 minutes
$_SESSION['end_time'] = $end;
?>
in the page where the quiz is submitted:
<?php
$now = time();
if ( $now <= $_SESSION['end_time'] ) {
// ok!
}
?>
Use the time() function to get a UNIX timestamp, which is really just a large integer.
The number returned by time() is the number of seconds since some date (like January 1, 1970), so to add $x minutes to it you do something like (time() + ($x*60)).
Since UNIX timestamps are just numbers, you can compare them with the usual comparison operators for numbers (< <= > >= ==)
time() will give you the current time in seconds since 1/1/1970 (an integer), which looks like it should be good.
To add x minutes, you'd just need to add x*60 to that, and you can compare it like any other two integers.
Source: http://us3.php.net/time
This is an old question but I wanted to provide an answer based on the PHP 5.2 DateTime class which I feel is much easier to use and much more versatile than any previous functions.
So how can i get the currentdatetime?
You can create a new DateTime object like this:
$currentTime = new DateTime();
But at this point, $currentTime is a datetime object and must be converted to a string in order to store it in a database or output it.
$currentTime = $currentTime->format('Y-m-d H:i:s');
echo $currentTime;
Outputs 2014-05-10 21:14:06
How can i add x minutes tocurrent this datetime?
You can add x minutes with the modify method:
$currentTime = new DateTime();
$addedMinutes = $currentTime->modify('+10 minutes');
echo $addedMinutes;
Outputs 2014-05-10 21:24:06
How can i comapare (<=) datetime ?
With the DateTime class, you can not only easily compare datetime objects, you can get the difference between them.
$currentTime = new DateTime('2014-05-10 21:14:06');
$addDays = $currentTime->modify('+10 days');
To compare
if ($currentTime >= $addDays) {
//do something//
}
$diffTime = new DateTime('2014-05-10 21:14:06');
$diff = $addDays->diff($diffTime);
$diff = $diff->format('There are %d days difference.');
echo $diff;
Outputs There are 10 days difference.

Adding time in PHP

I am pulling a datetime from a mysql db and i would like to add X hours to it then compare it to the current time. So far i got
$dateNow = strtotime(date('Y-m-d H:i:s'));
$dbTime = strtotime($row[0]);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
NOTE: I am using php 5.1.2 so date_add doesnt work (5.3.0)
You have quite a few options here:
1.
$result = mysql_query("SELECT myDate FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = strtotime("+4 hours", strtotime($myDate));
2.
// same first two lines from above
$fourHoursAhead = strtotime($myDate) + 4 * 60 * 60;
3.
$result = mysql_query("SELECT UNIX_TIMESTAMP(myDate) FROM table");
$myDate = mysql_result($result, 0);
$fourHoursAhead = $myDate + 4 * 60 * 60;
4.
$fourHoursAhead = strtotime("+4 hours", $myDate);
5.
$result = mysql_query("SELECT UNIX_TIMESTAMP(DATE_ADD(myDate, INTERVAL 4 HOUR))");
$fourHoursAhead = mysql_result($result, 0);
then i tried $dbTime + strtotime("4 hours"); but 4 hours seem to add 4hrs to the current time instead of raw 4hours. How do i add X hours to dbTime?
strtotime has an optional second argument. Provide a Unix timestamp there and the output will be relative to that date instead of the current date.
$newTime = strtotime('+4 hours', $dbTime);
You can also use the fact that Unix timestamps are seconds-based - if you know what four hours are in seconds, you can just add that to the time integer value.
time() and strtotime() result in unix timestamps in seconds, so you can do something like the following, provided your db and do your comparison:
$fourHours = 60 * 60 * 4;
$futureTime = time() + $fourHours;
strtotime("+4 hours", $dbTime);
The second argument is the timestamp which is used as a base for the calculation of relative dates; it defaults to the current time. Check out the documentation.
Edit:
For short periods of time, max 1 week, adding seconds to a timestamp is perfectly acceptable. There is always (7 * 24 * 3600) seconds in a week; the same cannot be said for a month or year. Furthermore, a unix timestamp is just the number of seconds that have elapsed since the Unix Epoch (January 1 1970 00:00:00 GMT). That is not effected by timezones or daylight-savings. Timezones and daylight-savings are only important when converting a unix timestamp to an actual calendar day and time.
I tend to use the time() function, and this page from the manual shows them displaying the date a week in the future:
http://us3.php.net/manual/en/function.time.php
Here's how I'd do it:
Pull the time from the database using the UNIX_TIMESTAMP() function.
The UNIX timestamp is in seconds, so add 4*60*60 to it.
Convert the modified UNIX timestamp to a date using PHP's localtime() or strftime() function.
query("SELECT UNIX_TIMESTAMP(someDatetimeColumn) ...");
. . .
$dbTimeAdjusted = localtime($row[0] + 4*60*60);
Probably the safest way to do the compare is right in the SQL
SELECT * FROM my_table WHERE someDateTimeColumn < DATE_ADD(NOW(), INTERVAL 4 hour)
And since you're assembling it in PHP, you can dynamically replace the "4 hour" bit with whatever your code needs to compare.
(Note: putting the entire calculation on the other side of the comparison to the column allows MySQL to do the calculation once per query, rather than once per row, and also use the table's index, if that column has one.)
Assuming that the timestamp returned by the DB is in SQL format, the following should work fine:
$dbTime = strtotime($row[0]);
$nowTime = time();
$future_dbTime = strtotime("+4 hours", $dbTime);
$diff_time_seconds = $nowTime - $dbTime;
if ($diff_time_seconds > 0) {
echo "The current time is greater than the database time by:\n";
$not_equal = true;
}
if ($diff_time_seconds == 0) {
echo "The current time is equal to the database time!";
}
if ($diff_time_seconds < 0) {
echo "The current time is less than the database time by:\n";
$not_equal = true;
}
if ($not_equal) {
$diff_time_abs_seconds = abs($diff_time_seconds);
echo date('h:m:s', $diff_time_abs_seconds);
}

PHP Time after midnight problem

I have an array of times I want to print out. I want the times that have passed lets say 12:00 clock to be 'greyed out'.
$theTime = '12:00';
if($theTime >= $time[$i])
{....}
02:30
03:50
03:20
04:50
05:45
19:45
20:00
20:50
20:55
21:25
21:30
22:00
22:45
23:55
00:50
00:55
Im doing a simple compare 12:00 a clock to each value.
The problem occurs when you change the time to after midnight for example 00:15. How can I calculate and print the list in order, when time has passed midnight?
if you pass midnight, more than one day is involved. this means that you have to include the information of day! what day is it? so in order to achieve what you want you should list/store more than just the time! if you store a datetime value, you will have no problems calculating time differences, since php will know in what order to put the times according to the day information.
for that look at the php datetime functions.
they will also help you to calculate differences!
Use unix timestamps. create a unix time stamp for midnight, and then compare all of the others to that. Then format it as a time when you print it out.
(A while since I used PHP, so can't remember quite how to do it, but should be simple. I know I have done something similar before. Take a look at http://php.net/time, http://php.net/manual/en/function.mktime.php and http://php.net/manual/en/function.date.php. Should be simple enough =)
As Svish said, you should use real timestamps, and you should also check the date change... here the, I think, more quick and easy way to know difference between 2 time (and date) :
<?php
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
echo "Differernce is $fullDays days, $fullHours hours and $fullMinutes minutes.";
?>
note the $date1 and $date2 have to be in mktime format, as :
int mktime ([ int $hour=date("H") [, int $minute=date("i") [, int $second=date("s") [, int $month=date("n") [, int $day=date("j") [, int $year=date("Y") [, int $is_dst=-1 ]]]]]]] )
I solved this problem as follows. It is not the best solution but at least it works:
$before_midnight = strtotime("23:59:59");
$before_midnight++; // this makes exact midnight
$start = strtotime("21:00");
$target = strtotime("03:00");
$after_midnight = strtotime("00:00");
for($i=$start; $i<$before_midnight; $i += 3600)
echo date("H:i", $i). "<br>";
for($i=$after_midnight; $i<=$target; $i += 3600)
echo date("H:i", $i). "<br>";
You have a string ('12:00') and are trying to compare it like a number.
http://us3.php.net/manual/en/language.operators.comparison.php
Like Svish and Paul said, you need to use integer timestamps.
$now = time(); // Get the current timestamp
$timestamps= array(strtotime('midnight'),
strtotime('07:45'),
...
);
foreach ( $timestampsas $time ) {
if ( $time >= $now ) {
// $time is now or in the future
} else {
// $time is in the past
}
}
You can format the timestamps with the date function.
Re. Svish's suggestion - strtotime() is handy for easily creating Unix timestamps relative to the current time, or any arbitrary time.
e.g. strtotime('midnight') will give you the unix timestamp for the most recent midnight.

Categories