Counting down days not showing the right number of days - php

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";

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]);

Go over 24 hours in a date?

I am working on project (a Google Transit feed) where I am required to provide the times for each stop on a bus route in the following common format: 21:00:00 and so forth.
Problem is, if times continue past midnight for a given trip, they require it to continue the hour counting accordingly. They explain quite specifically that 02:00:00 should become 26:00:00 and 03:45:00 should become 27:45:00 etc.
I am baffled on how to display such with any of the date() or strtotime() functions.
The only thing I can think of in my particular situation would be to function match and replace any strings in my output between 00:00:00 and 04:00:00, as that would clearly mean (again, for me only) that these are trips originating before midnight, but I don't feel that's the correct way.
Well seeing as it's only displaying on the page, you can
firstly get your date from where ever
Let's say $date = 00:00:00
$exploded_date = explode(":", $date);
This takes $date and puts it into an array so
$exploded_date[0] is hh
$exploded_date[1] is mm
$exploded_date[2] is ss
Then what you can do is use ltrim() to remove the leading 0 from 00 to 04 $exploded_date[0] - This makes it comparable in the if statement I'll do after
if($exploded_date[0] <= 4) {
$exploded_date[0] = ltrim($exploded_date[0], "0");
$exploded_date[0] = $exploded_date[0]+24;
}
Then you can implode the array back together into one string
$date = implode(":", $exploded_date);
// if the hour is 00 to 04 it will come out as 24 to 28
// e.g. 24:35:30
echo $date;
Despite giving you an answer. It's a silly thing to be doing, but it's not your choice so here you go :)
The way you display something doesn't necesarily has to be the same way you store something.
I don't know how you calculate the times, but assuming you have a start date and time, and some interval, you could calculate the end time as follows:
date_default_timezone_set('Europe/London');
$start_datetime = new DateTime('2014-11-11T21:00:00');
$next_stop = new DateTime('2014-11-12T02:00:00');
echo $start_datetime->format('Y-m-d H:i'); // 2014-11-11 21:00
echo $next_stop->format('Y-m-d H:i'); // 2014-11-12 02:00
$interval = $start_datetime->diff($next_stop);
// display next stop: 2014-11-11 26:00
echo ($start_datetime->format('Y') + $interval->y) .'-'
. ($start_datetime->format('m') + $interval->m) .'-'
. ($start_datetime->format('d') + $interval->d) .' '
. ($start_datetime->format('H') + $interval->h) .':'
. ($start_datetime->format('i') + $interval->i);
What I'm doing: create the start date (& time) and the datetime of the next stop. With the DateTime::diff() function I'm calculating the difference, and then, only for display (!) I add up each year, month, day, hour and minute to the datetime year, month etc. of the next stop.
This way you can still store your dates and times in a way every human being and computer system will understand (because let's be honest; to represent a time as 27:45 PM is quite ridiculous...)
I don't know if you only want the hours to be added up and roll over the 24 hour, or also days in a month etc. It's up to you how you handle these cases. Good luck!

Convert Date to Hours only using PHP

I would to add a certain amount of hours to a date time using PHP.
I am interested to show the result only using hour format.
For example, I add 8 hours to a date time as follow:
$result= date("H:i", strtotime('18:00') + 8*3600);
But I got as result value 01:00, but I would get 26 as result..
Can you help me please, I could not find the solution :(
Thank you all
It's easier with DateTime:
$date = new DateTime('18:00:00');
$date->modify('+8 hours');
echo $date->format('H:i');
Edit: Maybe I don't understand the question then. If you want to get 26, then you can use something like:
$date = new DateTime('18:00:00');
echo $date->format('H') + 8;
Basic PHP dates math. strtotime() returns a unix timestamp, which is number of seconds since the epoch, midnight January 1,1970.
date() takes those timestamps and formats them into whatever representation you want. But 'H' is NOT "hours since time zero". it's "hours of the day". If you have a timestamp that represents Jul 8/2014 12 noon, then H is going to be 12, because it's noon. It's not going to be 50 bajillion hours since Jan 1/1970.
e.g.
Jul 8/2014 11pm + 3 hours = Jul 9/2014 2am.
date('H' of Jul 9/2014) = 2, not "14"

Understanding date processing with strtotime

I'm trying to get my head round someone else's code which they've written for handling the dates of when news stories are published. The problem has come up because they are using this line -
$date = strtotime("midnight", strtotime($dateString));
to process a date selected using a jquery calendar widget. This works fine for future dates, but when you try to use a date which is in the previous calendar year, it uses the current year instead. I think this is due to "midnight" finding the closest instance of the selected day and month.
I could remove the "midnight", but I'm not sure what the repercussions of this would be - is there a reason that the midnight could be there?
EDIT: this is the full block of code which handles the date. The date contains the time, which allows the user to publish an item at a specific time.
$array['display_date'] = '24 October, 2011 17:30';
$string = $array['display_date'];
$dateString = substr($string, 0, -5);
$timeArray = explode(':', substr($string, -5));
$hours_in_secs = 60 * 60 * $timeArray[0];
$mins_in_secs = $timeArray[1];
$date = strtotime("midnight", strtotime($dateString));
$timestamp = $date + $hours_in_secs + $mins_in_secs;
//assign timestamp to validation array
$array['display_date'] = $timestamp;
echo $array['display_date']; // Output = 1351094430 (Oct 24 2012 17:00:30)
This really depends on what $dateString contains. Assuming your jQuery widget delivered the time portion as well, your colleague likely wanted to remove the time portion. Compare the following:
echo date(DATE_ATOM, strtotime('2010-10-01 17:32:00'));
// 2010-10-01T17:32:00+02:00
echo date(DATE_ATOM, strtotime("midnight", strtotime('2010-10-01 17:32:00')));
// 2010-10-01T00:00:00+02:00
If your widget doesnt return the time portion, I dont see any reason for setting the date to midnight, because it will be midnight automatically:
echo date(DATE_ATOM, strtotime('2010-10-01'));
// 2010-10-01T00:00:00+02:00
Note that all these are dates in the past and they will result in the given year in the past, not the current year like you say. If they do in your code, the cause must be somewhere else.
Will there be repercussions when you change the code? We cannot know. This is just one line of code and we have no idea of any context. Your unit-tests should tell you when something breaks when you change code.
EDIT after update
The codeblock you show makes no sense whatsoever. Ask the guy who wrote it what it is supposed to do. Not only will it falsely return the current year for past years, but it will also give incorrect results for the minutes, e.g.
24 March, 2010 17:30 will be 2012-03-24T17:00:30+01:00
I assume this was an attempt at turning 24 March, 2010 17:30 into a valid timestamp, which is in a format strtotime does not recognize. But the approach is broken. When you are on PHP5.3 use
$dt = DateTime::createFromFormat('d F, Y H:i', '24 March, 2010 17:30');
echo $dt->format(DATE_ATOM); // 2010-03-24T17:30:00+01:00
If you are not on 5.3 yet, go through https://stackoverflow.com/search?q=createFromFormat+php for alternate solutions. There is a couple in there.

March 14th not 86400 seconds long?

In my web application, I have users input a date in a simple textbox. That input (after being sanitized, of course), is run through strtotime(), and 86399 is added to it, to make that timestamp the end of the day written (11:59:59). This is for due date purposes (so if the date passes, the application raises a flag)
For the days I tested, it worked...
January 5th saved as january 5th, at the end of the day.
March 13th saved as March 13th
March 15th saved as March 15th
March 14th, for whatever reason, saved itself as March 15th.
Is March 14th mysteriously a couple seconds short or something??
Update: Thanks to oezi for the solution - worked like a charm. Code as requested:
Old code:
if ($_POST['dateto'] != '') {
$dateto = strtotime(mysql_real_escape_string($_POST['dateto'])) + 86399;
}
New code:
# Offset to "end of day"
list($y,$m,$d) = explode('-',date("Y-m-d",strtotime($_POST['dateto'])));
$d++;
$dateto = strtotime($y . '-' . $m . '-' . $d) - 1;
March 14, 2010 is the day Daylight Saving Time begins in the United States. So if you're doing math in the local time zone, March 14 is only 23 hours long.
I would assume because this is the beginning of daylight savings time
Like others said, this is because of daylight saving time. To solve this problem, you could do this:
<?php
list($y,$m,$d) = explode('-',date("Y-m-d",strtotime($date_from_user)));
$h = 23;
$i = 59;
$s = 59;
$mytimestamp = "$y-$m-$d $h:$i:$s";
?>
What database are you using? there has to be a better way to do this (most date manipulation commands are database specific). In SQL Server, I'd just add 1 day to the date and then subtract 1 second:
DECLARE #YourDate datetime
SET #YourDate='2010-03-14'
SELECT DATEADD(ss,-1,#YourDate+1)
OUTPUT:
-----------------------
2010-03-14 23:59:59.000
(1 row(s) affected)
for what it is worth, I'd much prefer to have a condition: < NextDay than <=CurrentDay12_59_59
In all time zones that "support" daylight savings time, you'll get two days a year that don't have 24h. They'll have 25h or 23h respectively. And don't even think of hardcoding those dates. They change every year, and between time zones.
Oh, and here's a list of 34 other reasons that you hadn't thought about, and why you shouldn't do what you're doing.
http://tycho.usno.navy.mil/leapsec.html
Not all days are 86400 seconds long.
This is a rare event. And (historically) never scheduled in March.

Categories