I'm trying to get the time difference in milliseconds.
$_SESSION['startTime'] = time();
$to_time = time();
//I call the code from here after a delay, say 4 seconds
$from_time = $_SESSION['startTime'];
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
print_r( $d1->diff($d2));
I print the result after 4 seconds and the result is somewhat like this:
DateInterval Object
(
[y] => 4 //---- Problem, this value should be +
[m] => 0 // |
[d] => 0 // |
[h] => 0 // |
[i] => 0 // |
[s] => 0 //<-here-----------------------------+
[invert] => 1
[days] => 1461
)
[s] should have been 4. why the 4 is in the year section?
What am I doing wrong?
UPDATE - Solved
$to_time = (microtime(true));
$from_time = ( $_SESSION['startTime']);
$diff = $to_time - $from_time;
print $diff;
Prints
3.xxxxxx
You must specify the formatting. You're sending in a unix timestamp into DateTime, therefor:
$d1 = new DateTime($from_time);
$d2 = new DateTime($to_time);
Becomes
$d1 = new DateTime('#'.$from_time);
$d2 = new DateTime('#'.$to_time);
The # symbol tells DateTime that I'm using a Unix Timestamp.
The constructor for DateTime accepts a string as a parameter not a timestamp, which is why you are seeing the "strange behaviour".
You need to expressly set the timestamp after insantiating a DateTime object:-
$from_time = $_SESSION['startTime'];
$d1 = new DateTime();
$d1->setTimestamp($from_time);
Related
I want to know if a timestamp stored in my database as a bigint (I'm using mariaDB) is already old comparing it to the current date, there's one example:
I have this timestamp stored in my db = 1560499685530 but for some reason, it is a string when I fetch it from my db so I got this error when trying to set its timestamp (setTimestamp($timestamp))
DateTime::setTimestamp() expects parameter 1 to be integer, string
given
I tried using intval but my timestamp seems to be too long to be int because when I use inval it returns another int, smaller than mine, I guess that's the PHP int cap
I want my PHP to print if it's already an old date comparing it to the current date and wrote this code
$qBloqueo = mysqli_query($conn, "SELECT * FROM dates WHERE idUsuario = '$idUsuario'") or die(mysqli_error($conn));
$timestamp = mysqli_fetch_assoc($qBloqueo);
$timestamp = intval($timestamp['timestamp']); // Getting the timestamp from my db which is a string, still dunno why, in my db it's a bigint
$today = new DateTime();
$expireDate = new DateTime();
$expireDate->setTimestamp($timestamp);
if($today->format("Y-m-d") > $expireDate->format("Y-m-d")) {
print('Old date ^u^');
} else {
print('Not yet');
}
How can I use a timestamp to make a date obj without been a int or there is any way to convert it from a string to int? I just want to make a date from a string timestamp so I could compare it to the current date
If only type is concern then you can type cast variable like:
$timestamp = (int) $timestamp['timestamp'];
If you're looking for difference between two times
<?php
$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');
?>
Output :
1 second(s)
Now to find difference between two timestamps
/* PHP/5.5.8 and later */
$start = new DateTimeImmutable('2016-04-20 00:37:15');
$end = $start->modify('+7 days');
$diff = $end->diff($start);
print_r($diff);
Output :
DateInterval Object ( [y] => 0 [m] => 0 [d] => 7 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 1 [days] => 7 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
To convert date timestamp into millisecond
$yourdate = '2016-03-22 14:30';
$stamp = strtotime($yourdate); // get unix timestamp
$time_in_ms = $stamp*1000;
print_r($time_in_ms);
Output :
1458657000000
You can convert both times into millisecond and find which one is greater.
I hope this helps in some way
I have a leave system where user select dates from and to dates let say 2018-02-26 - 2018-03-03 that is 6 days in total. On our portal it shows all users that is on leave. supposing that this user applied for 6 days leave, How am I going to display this user for 6 days on our portal?below is my code it works well but is show only for the current date.
$currentDate = date('Y-m-d');
$lf = Leave::where('leave_from', $currentDate)
->where('status', 'approved')
->get();
I am using eloquent. thanks
// Specify the start date. This date can be any English textual format
$date_from = "2018-02-03";
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp
// Specify the end date. This date can be any English textual format
$date_to = "2018-02-10";
$date_to = strtotime($date_to); // Convert date to a UNIX timestamp
// Loop from the start date to end date and output all dates inbetween
for ($i=$date_from; $i<=$date_to; $i+=86400) {
echo date("Y-m-d", $i).'<br />';
}
You can use datetime function in PHP.
$first_date = new DateTime($currentDate);
$last_date = new DateTime($if);
$difference = $first_date->diff($last_date);
echo $difference->d.' days;
if you want month and year use $difference->m and $difference->y.And if you want accurate days even dates are negative use below one.
$result = $first_date->diff($last_date)->format("%r%a");
source:/ datetime
You can use date_diff() function:
$interval = date_diff($currentDate, $lf);
echo $interval->format('%d');
more on: http://php.net/manual/en/function.date-diff.php; https://www.w3schools.com/php/func_date_date_diff.asp
You can use DATEDIFF to get difference directly from query.
Select abs(DATEDIFF(`date_to`,`date_from`)) as diff from leaves;
In laravel you can write it as
$lf = Leave::where('status', 'approved')
->select(DB::raw("abs(DATEDIFF(`date_to`,`date_from`)) as diff"),"*")
->get();
Be sure to use where('leave_from', $currentDate), I think it's not necessary.
You can use DateTime function of PHP
in your case
$currentDate = date('Y-m-d');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result like
DateInterval Object ( [y] => 0 [m] => 0 [d] => 5 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 5 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
$many_days=0;
$date_from = "2018-02-26";
$date_to = "2018-03-03";
for ($i=strtotime($date_from); $i<=strtotime($date_to);
$i+=86400) {
$many_days++;
}
echo "leaves $many_days";
I am trying to calculate time different between 3 different dates
1. Start date
2. End date
3 current date
I have been researching on how to calculation but couldn't find any exact example.
Any assistance in resolving this would be appreciated.
function getweekSartEndDate($date){
$cur_date = strtotime($date); // Change to whatever date you need
// Get the day of the week: Sunday = 0 to Saturday = 6
$dotw = date('w', $cur_date);
if($dotw>1){
$pre_monday = $cur_date-(($dotw-1)*24*60*60);
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==1){
$pre_monday = $cur_date;
$next_sunday = $cur_date+((7-$dotw)*24*60*60);
}
else if($dotw==0){
$pre_monday =$cur_date - (6*24*60*60);;
$next_sunday = $cur_date;
}
$date_array = array();
$date_array['weekStart'] = $pre_monday;
$date_array['weekEnd'] = $next_sunday;
return $date_array;
}
The above is the example code i got so far, and i was able to get the start and end dates of a week as seen below:
$weekStart = date('Y-m-d H:i:s', $weekInfo['weekStart']);
$weekEnd = date('Y-m-d H:i:s', $weekInfo['weekEnd']);
My challenges is how to get the time difference in 'Y-m-d H:i:s' date format from the current time.
You can use
$currentDate = date('Y-m-d H:i:s');
$currentDate = new DateTime($currentDate);
$leaveDate = new DateTime($leaveFrom);
$difference = $currentDate->diff($leaveDate);
You will get result as follow
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 0 [s] => 0 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
You need basic knowledge on how to do number comparisons in PHP.
Convert your date strings to a UNIX-timestamp with strtotime
$d = strtotime("19/10/2016 14:48:21");
// 1519646232
When the dates are in UNIX-timestamp format, it's easy to compare them with any regular comparison operators as int numbers.
EDIT
Difference in seconds:
$diffBetweenStartAndNow = strtotime( $date_array['weekStart'] ) - time();
$diffBetweenEndAndNow = strtotime( $date_array['weekEnd'] ) - time();
I need to work out the number of months between a date like this:
$inputDate = '09/08/2016';
that is entered in the MM/DD/YYYY format, and the current date, e.g.:
$today = date("m/d/Y");
I've been looking at the date_diff but can't seem to get the syntax right here and appreciate any help here.
You can use DateTime and diff
$datetime1 = new DateTime();
$datetime2 = new DateTime('09/08/2016');
$interval = $datetime1->diff($datetime2);
$months = $interval->format('%m months'); # you can also use %a days %h hours %i minutes %s seconds
echo $months;
# 8 months
# optimally you can use:
# echo $datetime1->diff($datetime2)->y*12;
# or
# echo $interval->m
Update based-on comments:
$datetime1 = new DateTime();
$datetime2 = new DateTime('09/08/2015');
$interval = $datetime1->diff($datetime2);
echo (($interval->format('%y') * 12) + $interval->format('%m')) . " full months difference";
Note:
A DateInterval Object looks like:
DateInterval Object
(
[y] => 3
[m] => 5
[d] => 15
[h] => 0
[i] => 0
[s] => 0
[invert] => 0
[days] => 1264
)
That's why we've to multiply the number of years * 12 and add the months in order to get the difference in months. Strange, but this is how it works...
I need your help in how to subtract the last_modified and the final_manuscript_date in the following array:
Array (
[chapters_id] => 10736
[last_modified] => 2010-12-21 15:01:55
[steps_id] => 3
[sub_step_id] => 0
[steps_position] => 1
[final_manuscript_date] => 2010-09-27
)
So I can in this case get a value of N days between the dates 2010-12-21 and 2010-09-27?
Can't you simply do:
$diff = strtotime($arr["final_manuscript_date"]) - strtotime($arr["last_modified"]);
$days = $diff / 84600; // to get # of days, you can round them off or use ceil/floor
If you have 5.3+:
$date1 = new DateTime("2010-09-27");
$date2 = new DateTime("2010-12-21");
$interval = $date1->diff($date2);
echo $interval->d //returns days.
Have you checked strtotime?
http://php.net/manual/en/function.strtotime.php