Wrong time with DateTime - php

I am creating notifications system and here is a task: get the time, when a notification was sent. I mean the following: 1 minute ago, 13 hours ago and so on. I have already made up a script but it shows wrong time. For example instead of showing '5 minutes ago' it shows '9 hours ago'. Here is the alrogithm:
Get old timestamp from database. Old timestamp is the time, when a
notification was sent.
Get current users timestamp.
Get difference between them.
Echo result.
Here is the PHP code:
$fromdb = '1503737539'; //For this example think, that this variable is from database.
//This timestamp was created 5 minutes earlier, so in result it should show '5 minutes ago'.
$curr = new DateTime();
$got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));
$interval = $curr->diff($got2);
echo $interval->format('%d')." days ".$interval->format('%h')." Hours ".$interval->format('%i')." Minutes ".$interval->format('%s')." Seconds";
The output is:
0 days 9 hours ....
instead of
0 days 0 hours 5 minutes ....
How can I fix that? I guess that this is a problem with timezones. But how can I guess guests timezone though?
Update:
Change code:
$got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));
And interesting fact: The more is actual difference, the less time it shows in output. For example: Old timestamp was created at 8:00 am, and current is 15:00 pm, it shows 0 days 1 hour in output.

I think
date('Y-m-d',$fromdb)
broke your code.
Try
$got2->setTimestamp($fromdb)

there is mistake in your code. you format date without hours, minutes and seconds
$got2 = new DateTime(date('Y-m-d',$fromdb));
try
$got2 = new DateTime(date('Y-m-d H:i:s',$fromdb));

Try
$date = new DateTime(); echo $date->format('U = Y-m-d H:i:s');
$date->setTimestamp(1171502725);
echo $date->format('U = Y-m-d H:i:s');

Related

Laravel get total time workerd by employee between two dates using carbonInterval or carbon php

i have time shifts which are assigned to the user. Suppose a night shift starting time is 21-00-00 pm of one july and its ending time is 03-00-00 am of 2nd July. Now i want to get total time a employee worked by adding start time to end time which is equal to 6 hours and i should get six hours. I have tried following code which is working fine for current date like it will give me exact 6 hours if start time is equal to 15-00-00 pm of 1 july to 21-00-00 pm of 1 july but it will fail when shifts exists between two dates as i mentioned above.
$attendance_start_time = \Carbon\Carbon::parse($shift->start_time);
$attendance_end_time = \Carbon\Carbon::parse($shift->end_time);
$total_attendance_time=$attendance_end_time->diffInSeconds($attendance_start_time,true);
\Carbon\CarbonInterval::seconds($total_attendance_time)->cascade()->forHumans()
i am expecting six hours but it is giving me following result
18 hours
i want exact six hours
Not sure if it will fully solve your problem, but check out this :
\Carbon\CarbonInterval::seconds(4100)->cascade()->forHumans(['aUnit' => true]);
UPD:
It might be this solution will work in your case, but make sure that you have tested all of the edge-cases:
$startTime = \Carbon\Carbon::parse('2022-07-02 19:00');
$endTime = \Carbon\Carbon::parse('2022-07-02 19:30');
$diff = $startTime->diffInSeconds($endTime);
if ($endTime->greaterThanOrEqualTo($endTime) && ! $endTime->isSameDay($startTime)) {
$diff = $startTime->diffInSeconds($endTime->addDay());
}
$humanReadable = \Carbon\CarbonInterval::seconds($diff)->cascade()->forHumans(['aUnit' => true]);

PHP DateInterval - Where is string $format parameter defined?

Been trying to figure out just how to add hours, days, weeks and years to a date. Found a few examples that work, but I have NO idea why.
$dt->add(new DateInterval('P1Y')); 'P1M', 'P1D' all add one year, month and day. 'P1H' or 'P1S' throw exceptions.
Been reading all about DateTime class and reading the https://www.php.net/manual/en/dateinterval.format.php page, NO WHERE can I find anything that explains what the 'P' part of that format string is.
Where is some decent documentation on this??? It should not take hours to figure out how to add a few days to a date!!
The P stands for period. If you want to define an interval based on hours or minutes check this example:
$interval = new DateInterval('PT1H');
Here, $interval represents a time interval of 1 hour.
For example, to add an hour to an existing date:
$date = new DateTime();
$date->add($interval);

PHP - Resetting Stats

I'm using a WordPress plugin that re-sets its stats every 7 days using the following line of code:
$keep_time = 60*60*24*7; // 7 days for now (TODO: admin setting)
Could someone help me to modify the code to re-set the stats every 6 hours or every other day?
I did try to try to change the 7 to 1 but it doesn't work. Probably the solution is very simple, but unfortunately I'm not a PHP programmer.
Thanks everyone for answering my question, wanted to give a vote but I don't have enough 'reputation'
For 6 hours use:
$keep_time = 60*60*6;
For 2 days use:
$keep_time = 60*60*24*2;
The value is in seconds. 60*60 is the number of seconds in an hour. Then you multiply by the number of hours you want. If you want multiple days, you multiply by 24 hours in a day, and then the number of days.
I like DateTime() and DateInterval() for this. Not only is it clearer but it handles daylight savings time and leap years as well as those pesky last days of the month.
7 Days:
$start_time = new DateTime(); // "now" as an example
$keep_time = new DateInterval('P7D'); // 7 days
$start_time->add($keep_time);
echo $start_time->format('Y-m-d');
6 Hours
$start_time = new DateTime(); // "now" as an example
$keep_time = new DateInterval('PT6H'); // 6 hours
$start_time->add($keep_time);
echo $start_time->format('Y-m-d');
$keep_time = 60(sec)*60(min)*24(hours)*7(days);
you need to do
$keep_time = 60*60*6;

Counting down days not showing the right number of days

I need help.. Is this right?
Start Date: Mar 16, 2014
End Date: Mar 19, 2014
Results: 2 Days
$plantEnd = get_the_author_meta('plantEnd', $sellerID );
$plantStart = get_the_author_meta('plantStart', $sellerID );
$future = $plantEnd;
$d = new DateTime($future);
echo $d->diff(new DateTime())->format('%a').' Days';
Why does it says 2 days? Isn't it 3 days? Im confused..
Since you aren't actually using $plantStart in your code and instead using the current time, you're basically getting a difference between now (the time the script was run, on server's time zone) and the start of Mar 19, 2014 (0h:0m:0s). So what you are really getting is something like 2 days 5 hours 3 minutes 25 seconds (depending on when you run it vs. server time.
for example, when I run this locally:
$d->diff(new DateTime())->format('%d:%H:%i:%s');
I get 2:04:59:25
So there's more to it than just getting that "2" returned.. you're just not formatting for it.
And again, you aren't actually using the $plantStart anywhere either. So if you were to do this:
<?php
$plantEnd = '2014-03-19';//get_the_author_meta('plantEnd', $sellerID );
$plantStart = '2014-03-16'; //get_the_author_meta('plantStart', $sellerID );
$future = $plantEnd;
$d = new DateTime($future);
echo $d->diff(new DateTime($plantStart))->format('%d:%H:%i:%s');
?>
You will see it outputs 3:00:0:0 (or you could continue to just use %d and get the "3"). This is because $plantStart (presumably - based on your post) just specifies yyyy-mm-dd, so passing just the yyyy-mm-dd value will put the hh:mm:ss at 0:0:0 (beginning of day) , so it will be a full day's calculation, which has the effect of "rounding up" to the whole day increment.
I have a feeling that it's actually 2 days, someodd hours, and someodd minutes, or something to that effect. Because you're formatting to just do days, you're losing the nuances. I'd change the code to say "2.4 days" (and for the life of me I can't remember how I did this in the past...)
EDIT: in the past I have simply used date() instead of DateTime().
I did a little research, and you might want format('%d')." Days";

How to work out time elapsed from this datetime stamp and return it in either minutes, hours or days as appropriate

I'm dealing with an api which is returning the date time stamp exactly as follows:
Mon, 14 May 2012 14:14:11 +0000
I would like process this so php works out how many minutes ago this was if the number of minutes is less than 60 else how many hours ago it was if the number of hours is less than 24 else the number of days.
Dates will never be older than a few weeks.
Thanks.
You want to use the DateTime class. It can parse that date.
$now = new DateTime('now');
$dt = new DateTime('Mon, 14 May 2012 14:14:11 +0000');
$interval = $now->diff($dt);
$minutes = $interval->format('%i');
Note that 'now' will be in your current time zone so you might want to pass the DateTimeZone parameters as well. More info is here: http://php.net/DateTime
The class should already be built into your PHP. You won't need to include it.

Categories