I have been googling last 2 hours and I figured out that the problem is related to Unix epoch.
What I want to do is a count down in php. As you can see below, (Gave them letters to refer them easily).
B minus C is equal to A. But it gives me this: "31/12/69 19:00:08" but I would like to have "00/00/00 00:00:08".
(A) 31/12/69 19:00:08 = (B) 25/03/15 00:13:26 - (C) 25/03/15 00:13:18
And this problem cause a problem in my count down. When I wanna count down from 10:00 (Min, Sec), it starts counting down from 60:00 and when it reaches 50:00 count down stops. So it works! after 10 min it stops but the problem is, it counts down from 60. So, it is caused from unix epoch I guess. If I can initialize the unnecessary part, in the date, to zero or null I can fix the problem.
$pastTime = $currentTime - $row['startTime'];
if($pastTime >= $row['durationTime']){
$processStatus = "Completed";
$remainingTime = 0;
}else{
$processStatus = "in Process";
$remainingTime = $durationTime - $pastTime;
}
echo "<td>" . date('i:s', $remainingTime) . "</td>";
echo "<td>$processStatus</td>";
echo "</tr>";
This is some part of my code. So, I am having problem when I do this; date('i:s', $remainingTime). All the variables you see, contains seconds which is generated by time() function.
You're not sharing any code, but I take it that you subtract two timestamps to figure out the difference in seconds, and then format the result as a unix timestamp.
The problem is in that last step. When you subtract the two numbers, you do get a (mostly) correct number, but then you decide to use (presumably) date() for display.
Instead, you may want to try to use two DateTime objects, use diff to get the difference (as a DateInterval object) and then use DateInterval::format to get the format you actually want.
Related
I only have basic PHP knowledge and I'm using PHP+Mysql and trying to check the difference in days between 2 dates; the 1st date is formatted by myself in the script as a string:
$f_entrega=$_POST['year1']."-".$_POST['month1']."-".$_POST['day1'];
The second date ($f_dock) which is the one causing the issue is taken from the mysql database which column is in DATE format. To compare the dates I do the following:
if(!empty($_POST["id"])){
$f_entrega=$_POST['f_entrega_a']."-".$_POST['f_entrega_m']."-".$_POST['f_entrega_d'];
$f_entr=$f_entrega;
$mysqli=conectar();
$resultado = $mysqli->query("SELECT id,f_dock FROM pt");
$row = $resultado->fetch_assoc();
for ($i=0;$i<count($ids);$i++){
do{
if ($ids[$i]==$row["id"]){
$f_dock=$row["f_dock"];
break;
}
} while ($row = $resultado->fetch_assoc());
$error=0;
var_dump($f_dock);
$f_dock=strtotime($f_dock);
$f_dock=date('Ymd',$f_dock);
$f_entrega=$f_entr;
$f_entrega=strtotime($f_entrega);
$f_entrega=date('Ymd',$f_entrega);
$f_dock=DateTime::createFromFormat('Ymd',$f_dock);
$f_entrega=DateTime::createFromFormat('Ymd',$f_entrega);
$dias_vendor=date_diff($f_dock,$f_entrega);
$tat=$dias_vendor->format('%R%a');
Sometimes it works correctly, but other times I get Warning: strtotime() expects parameter 1 to be string, object given in [first line] and $tat is not correctly calculated and has strange values.
I've tried different solutions like $f_dock=(string)$f_dock before but finally the convertion always fails in some cases. Thanks in advance for any tip.
The error that you are getting is because the string you are entering is not a valid string for the strtotime() function to convert.
For instance 2015-08-31 will convert just fine, as will today, tomorrow or +7 days.
For more specific help you will need to tell us what the value of $f_dock is (as Marcos says in his comment, var_dump($f_dock) will get you this).
However, on to the solution:
$date1 = strtotime($f_dock); //timestamp in seconds
$date2 = strtotime($f_entrega); //same for the second date
$difference = $date1 - $date2; //difference in seconds between the dates
$days = floor($difference/86400);
86400 is the number of seconds in a day, so find out how many seconds difference there is, then see how many days worth of seconds are in there and use floor() to round the number down. Job done.
I'm wanting to display on a php page the difference between the current server time and a datetime row plus a row that has milliseconds in it, so I guess the equation would look kind of like ((Datetime+Milliseconds)-Server Time).
The only problem is, I'm not sure how to do it in code. I can currently get the difference between the datetime row and the current time with echo strtotime($row['date_added']) - time(); When I try adding the row that contains the milliseconds, date_mil, I get a really long number.
The date in the row date_added looks like 2012-05-25 16:55:06 and the value of the date_mil is around 218238.
I'm still learning how to do all of this, and this has me confused. Thanks for the help!
I just solved my own problem.
$difference = time() - strtotime($row['date_added']);
$milliseconds = round(($row['date_mil']) * .001);
echo $milliseconds - $difference;
This seems like a fairly simple question, but I'm having trouble with it!
In my database, I have two fields that have times in them. Let's say one field, named clockin, reads "2:29:39 pm," and another field, named clockout, reads "2:29:39 pm."
Then I have two other fields, one titled "breakin" which reads 2:28:37 pm and breakout which reads "2:28:55 pm".
I want to subtract breakout from break in to get the difference, and then take that number and subtract it from the difference between clockin and clockout.
How can I do this? Here's what I've tried:
$clockout = new DateTime($row['clockout']);
$clockin = new DateTime($row['clockin']);
$diff = $clockout->diff($clockin);
$on_the_clock = sprintf('%d hours, %d minutes, %d seconds', $diff->h, $diff->i, $diff->s);
$breakin = new DateTime($row['breakin']);
$breakout = new DateTime($row['breakout']);
$diff2 = $breakout->diff($breakin);
$break = sprintf('%d hours, %d minutes, %d seconds', $diff2->h, $diff2->i, $diff2->s);
That gives me two differences, but then I don't know how to subtract one from the other.
Thanks for any help!
Judging by your existing code I'm assuming your running PHP > 5.3 with the DateTime class.
In which case check out DateTime->sub(). You can use it to subtract the DateInterval returned from the break from clock out. Then do the difference between clock in and clock out. That would give you the total time worked.
I've used strtotime() for such problems. It produces pure number values in the form of the Unix timestamp. I'm not experienced with DateTime() but I prefer Unix timestamps since it represents number of seconds and can be converted back into a string or user-friendly format using date() if necessary.
I find storing Unix timestamps in the database is easier to manipulate as well. A user-friendly format isn't necessary until it needs to be displayed to the user.
[http://php.net/manual/en/function.strtotime.php][1]
I need to compare two dates to show an edit link if it is within 5 mins after the post was made, in PHP. If more than 5 minutes have passed, don't show anything.
$answer_post_date = get_the_time("Y-m-d");
$current_date = date("Y-m-d");
$formated_current_date = strtotime($answer_post_date);
$formated_answer_post_date = strtotime($current_date);
At this point I have two values:
1274414400 ($formated_current_date)
1276056000 ($formated_answer_post_date)
I am not sure what to do next to check if the current date/time is > 5 mins from the answer post date.
Any suggestions would be great.
All I really need the answer to be is a Boolean (yes/no) and if yes, display the minuets left to show the link to edit.
You're only handling dates, how are you supposed to know if the difference is 5 minutes?
Anyway, I'd say the majority of the PHP code that uses the default PHP functions is at least somewhat broken. The problem is you, despite a unix timestamp storing the correct point in time something happens, it does not store timezone information. See here.
So, forget using only date and strtotime. Use the datetime extension.
Store in the database the Unix timestamp and the timezone (by timezone I mean e.g. Europe/Lisbon). Then:
$tz = new DateTimeZone($timezone);
$answer_post_date = new DateTime("$timestamp");
$answer_post_date->setTimeZone($tz);
$current_date = new DateTime("now", $tz);
$diff = $current_date->diff($answer_post_date);
if ($diff->format("a") > 0 ||
$diff->format("h") > 0 ||
$diff->format("m") >= 5) {
//more than 5 minutes have passed
}
Of course, for comparing dates, you can always compare the timestamps.
My understanding of what you need to do:
$delta = ($formated_current_date - $formated_answer_post_date) / 60; // in minutes
if ($delta < 5) {
// show $delta
}
EDIT: Like others pointed out, this alone will not fix all of the issues at hand. As I see it, the smallest change to your current code would be to use a date format with higher granularity - such as "Y-m-d H:i:s". This being enough, like others pointed out, is contingent on the post's date being in the same timezone as your system.
I don't see the need to do a round-trip to a string format and back, regardless of how efficient or reliable it is.
date() will default to calling time() which you can call directly and get the current time in seconds as a Unix epoch timestamp (which is what you're trying to end up with in $formated_answer_post_date). You need to look in the WordPress docs to find the equivalent based on the post's value.
Then you can do a simple comparison of seconds. 5 minutes is 300 seconds.
You will still need to check that the code can assume the timezones of both values will be the same.
I'm trying to calculate the number of days between two days, but I'm running into issues with Daylight Savings Time. Here's my code:
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date) - strtotime($old_date);
return $offset/60/60/24;
}
Works fine as long as the days are both within the same DST period:
echo date_diff('3/15/09', '3/18/09'); // 3
But not if they're further apart:
echo date_diff('11/15/08', '3/18/09'); // 122.95833333333
I want an even number of days, and don't care about DST. I suppose I could round the result, but that feels kludgy. Is there a better (easy) way? I don't want to have to write a whole day-parsing-and-counting-avoiding-leap-years thing if I can avoid it.
(Note: this has to run under php 5.1.6, so some of the date features in 5.3 may not be available.)
A bit more info: I'm going to take the offset and add it to other datetimes that are in a db, and I want only the day part to change, not the time part. Turns out rounding won't work, anyway, because when I do the adding it gets off by one hour in the other direction. Maybe there's a better approach to the whole problem....
Force the dates to live into a timezone without Daylight Savings Time, GMT/UTC:
function date_diff($old_date, $new_date) {
$offset = strtotime($new_date . " UTC") - strtotime($old_date . " UTC");
return $offset/60/60/24;
}
echo date_diff('3/15/09', '3/18/09'); // 3
echo date_diff('11/15/08', '3/18/09'); // 123
you could use http://ca3.php.net/date_default_timezone_set to set the timezone to GMT so there will be no offset.
Alternately, you can manually add an offset using the date('I',$timetamp)
if ( date("I") == 1 ) { // "WE ARE MDT";
$timeZone = "MDT";
} else {
$timeZone = "MST";
}
You can force rounding in a specific direction by using floor() or ceil().
I tried the 'UTC' code above. Didnt work for me. I stll got decimal values.
When there is daylight saving date within the date range the difference serial decimal portion will be either under .5 or over. when date range has day light saving going on 3/15 the decimal value is > .5 when daylight is going off date decimal < .5. so I just put the difference serial in a round() function and I get the whole numbers i need for number of days.