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.
Related
I have checked out the following question/responses:
How do I get the format of “yyyy-MM-ddTHH:mm:ss.fffZ” in php?
The responses include links to Microsoft documentation to format dates but these do not work in PHP.
The the top answer suggest
date('Y-m-dTH:i:s.uZ') //for the current time
This outputs
2013-03-22EDT12:56:35.000000-1440016
Background
I am working with an API which requires a timestamp in the format above. The API is based in the UK (GMT) and my server is in Australia (AEST).
The example given in the API documentation ask for the date to be in this format:
2011-07-15T16:10:45.555Z
The closest I can get to this is date('c') which outputs:
2014-07-03T16:41:59+10:00//Notice the Z is replaced with a time diff in hours
I believe the 'Z' refers to a Zone but it is not mentioned in the PHP documentation.
Unfortunatly when I post this format, the API is reading the time and taking 10 hours off. I get an error saying that the date cannot be in the past (as it is checking against the local time in Melbourne, but seeing a time 10 hours earlier).
I have tried trimming the timestamp to remove the +1000 which the API accepts, but the record is showing as created as 10 hours earlier.
I need to match the timestamp required but I cannot find any way to replicate the above output, in PHP for Melbourne, Australia. Any assistance is much appreciated.
First question on SO so please let me know how I have gone
Z stands for the timezone UTC and is defined in ISO-8601, which is your desired output format, extended by the millisecond part.
Before outputting the time, you'll need to transfer local times to UTC:
$dt = new DateTime();
$dt->setTimeZone(new DateTimeZone('UTC'));
then you can use the following format string:
echo $d->format('Y-m-d\TH-i-s.\0\0\0\Z');
Note that I've zeroed the millisecond part and escaped the special characters T and Z in the format pattern.
The 3 number last before Z is just the 3 decimal place of time in milliseconds
The function microtime(true) gave the current time in milliseconds, would output like 1631882476.298437
In this situation it would be .298Z
Examples
1652030212.6311 = .631Z
1652030348.0262 = .026Z
1652030378.5458 = .545Z
Codes
$milliseconds = microtime(true);
// Round to integer
$timestamp = floor($milliseconds);
// Get number after dots
$uuuu = preg_replace("/\d+\./", "", "$milliseconds");
// Get last 3 number decimal place
$u = substr($uuuu, 0, 3);
// Print date by the timestamp timestamp
echo date("Y-m-d\TH:i:s", $timestamp). ".{$u}Z";
With PHP, I am trying to convert a bunch of numbers into a a readable format, the thing is, I have no idea how/what format these are in or can be parsed in using the date() or time() functions in php. there are two of these as well.
(they're built from a total time spent online and time since last log-on)
onlinetime : 1544946 = 2w 3d 21h 9m
lastonline : 1397087222 = 1h 32m
does anyone know the way to get the two different times from the two different timestamps?
If you have a Unix timestamp, take a look at Convert timestamp to readable date/time PHP. The PHP documentation is here: http://php.net/manual/en/function.date.php.
For the online time, you could do modulo arithmetic to figure out the values for each, and then just make a string out of the result. Someone may have a nicer suggestion for this though.
I think John is right, the first is the number of seconds in the timespan listed. And the second certainly looks like a unix timestamp to me. So here's how you can get what you want from these sets of numbers:
1) For the first number, simply divide the number by the seconds in a given time span and use floor():
$timeElapsed = 154496; // in this case
$weeksElapsed = floor($timeElapsed / 604800);
$remainder = $timeElapsed % 604800;
$daysElapsed = floor($remainder / 86400);
etc...
2) For the second number, you can do the same thing by first getting the current timestamp and then subtracting the given timestamp from it:
$lastOnline = 1397087222; // again, in this case
$currentTimestamp = time();
$elapsedSinceLastLogin = $currentTimestamp - $lastonline;
$weeksSinceLastLogin = floor($elapsedSinceLastLogin / 604800);
etc...
Hey guys i'm trying to figure out how to subtract one time from another using php to get the amount of time left between the two times. So for example
time left = time1-time2
or
timeleft = 15:35-15:30
which would be equal to 5mins left.
Currently I am loading the two times like so.
time1 is coming from my database (which is the time we are waiting for, and in my case the time we are waiting for is the time for next update) and time2 is the current system time.
I tried using this code
$timeleft = $dbtime - $curtime;
$dbtime = time loaded from database.
$curtime = current system time.
But that just returns a 0.
Any help is appreciated thanks.
Use strtotime to turn the date string to unix timestamp.
$timeleft = strtotime($dbtime) - strtotime($curtime);
You have to convert both times into timestamp. One good function for that is the strtotime() http://php.net/manual/en/function.strtotime.php that try to convert a string into timestamp.
Then do your maths as you know and then just use the date() http://www.php.net/manual/en/function.date.php function to fomrat your time into anything you like
Use strtotime to convert strings to unix timestamps:
$timedifference = strtotime($dbtime) - strtotime($curtime); // or also
$timedifference = strtotime($dbtime) - time();
You negating one string from another - the result in 0 because (int)(string) = 0
Your must use like this
$dbtime = time();
// query
$timeleft = time() - $dbtime;
See also strtotime() function, if you date is parsed by it
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 have to sent an email when a user register email contain a link that is become invalid after six hours
what i m doing when email is sent i update the db with field emailSentDate of type "datetime"
now i got the curent date and time and has made to the same formate as it is in db now i want to find that both these dates and time have differenc of 6 hours or not so that i can make link invalid but i donot know how to do this
my code is look like this i m using hardcoded value for db just for example
$current_date_time=date("Y-m-d h:i:s");
$current=explode(" ",$current_date_time);
$current_date=$current[0];
$current_time=$current[1];
$db_date_time="2010-07-30 13:11:50";
$db=explode(" ",$db_date_time);
$db_date=$db[0];
$db_time=$db[1];
i do not know how to proceed plz help
<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
see http://docs.php.net/datetime.diff
edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.
What you can do is convert both of your dates to Unix epoch times, that is, the equivalent number of seconds since midnight on the 31st of December 1969. From that you can easily deduce the amount of time elapsed between the two dates. To do this you can either use mktime() or strtotime()
All the best.
$hoursDiff = ( time() - strtotime("2010-07-30 13:11:50") )/(60 * 60);
I'd rather work with a timestamp: Save the value which is returned by "time()" as "savedTime" to your database (that's a timestamp in seconds). Subtract that number from "time()" when you check for your six hours.
if ((time() - savedTime) > 6 * 3600)
// more than 6h ago
or
"SELECT FROM table WHERE savedTime < " . (time() - 6 * 3600)
This might be the solution to your problem -> How to calculate the difference between two dates using PHP?