Time duration remaining unix timestamp - php

I have a unix timestamp and a duration, such as a year. I'd like to find out how to determine how much time is remaining from the duration based off the start unix timestamp. I want it in monthes.
I imagine its something like:
duration convert to seconds.
minus start to today to seconds (elapsed)
minus elapsed from duration
convert remaining to remaining in seconds
change remaining to monthes and determine remainder to days
I'm sure thouhg theres a php solution which is more accurate and precise than my design i think.
UPDATE
I have a unix timestamp of 1564113711, which is July 26, 2019. Today is August 7,2019. I need to know how much time remains in monthes and days from July 26,2020 (one year from the start) to today, August 7, 2019, where the elapsed time is July 26,2019 to August 7,2019

The DateTime object and DateTime::diff have everything you need.
$timeStamp = 1564113711; //26. Juli 2019
$duration = "1 Year";
$endDate = date_create("#".$timeStamp)->modify($duration);
$diff = date_create("today UTC")->diff($endDate);
//output
if($diff->invert) {
echo "your time's up";
}
else {
echo $diff->y * 12 + $diff->m." Month and ".$diff->d. " Days";
//e.g. 10 Month and 24 Days
}

Related

phpExcel given timestamp instead of actual date in excel sheet [duplicate]

I want to read dates from an Excel File, but when I print
the dates to the screen I can only see one number instead Of
the date, why?
Excel file:
Result:
Excel treats dates as numbers, with the number representing the number of days after December 31 1899. So day 1 is January 1 1900, and day 43102 is January 3 2018. But wait... your data says January 2 2018! It turns out that Microsoft thinks that 1900 was a leap year and so day 60 is February 29 1900 when in the real world it was actually March 1. Anyway, what that means is that for dates after February 28 1900, you need to subtract one from the day number to get the correct date. So, to convert an Excel day number to a date in PHP, you use the following code:
$dayval = 43102; // you would read from your file here
$date = new DateTime('1899-12-31');
$date->modify("+$dayval day -1 day");
echo $date->format('Y-m-d');
Output:
2018-01-02
Please use this formula to change from Excel date to Unix date, then you can use "gmdate" to get the real date in PHP:
UNIX_DATE = (EXCEL_DATE - 25569) * 86400
and to convert from Unix date to Excel date, use this formula:
EXCEL_DATE = 25569 + (UNIX_DATE / 86400)
After putting this formula into a variable, you can get the real date in PHP using this example:
$UNIX_DATE = ($EXCEL_DATE - 25569) * 86400;
echo gmdate("d-m-Y H:i:s", $UNIX_DATE);
The 86400 is number of seconds in a day = 24 * 60 * 60. The 25569 is the number of days from Jan 1, 1900 to Jan 1, 1970. Excel base date is Jan 1, 1900 and Unix is Jan 1, 1970. UNIX date values are in seconds from Jan 1, 1970 (midnight Dec 31, 1969). So to convert from excel you must subtract the number of days and then convert to seconds

How to check how many days passed from timestamp - counting the days at midnight

I'm trying to know how many days have passed from a certain timestamp, but the problem is I can't set it up, so that after midnight will count it as another day.
Here is what I tried:
<?php
$now = time(); // or your date as well
$your_date = 1572123244;
$datediff = $now - $your_date;
echo round($datediff / (60 * 60 * 24));
If I put a timestamp of five minutes before midnight (1572134100), five minutes after midnight should appear that "one day passed"
The usual way of counting the days passed since a given timestamp would be something like this:
$dt = date_create_from_format('U', 1572046200);
$diff = $dt->diff(new DateTime());
echo $diff->days;
But this counts the full 24 hour periods as days. In your case you want to count calendar dates irrespective of the time of day. I would recommend then to ceil the timestamp to the midnight.
$dt = date_create_from_format('U', 1572047700);
$dt->setTime(0, 0); // set time to 00:00
$now = new DateTime('now', new DateTimeZone('UTC')); // time now, but in UTC
$now->setTime(0, 0); // set time to 00:00
$diff = $dt->diff($now);
echo $diff->days;
I am not sure about your current time zone, but timestamps are by nature in UTC, hence you should probably normalize your local time to UTC as well.
What this code does is it sets both today's date and the timestamp you are comparing against to the midnight of the UTC day and then calculates the difference between the two. Taking the time out of equation, this will always count the full 24 hour days.

Calculate time worked including brakes in PHP

I'm struggling to to write a PHP function that would calculate time difference between two hours (minus the brake) and the result would be in decimal format. My inputs are strings in 24-hour format (hh:mm):
$start = '07:00'; //started at 7 after midnight
$brake = '01:30'; //1 hour and 30 minutes of brake
$finish = '15:00'; //finished at 3 afternoon
//the desired result is to print out '6.5'
example 2
$start = '19:00'; //started late afternoon
$brake = '00:30'; //30 minutes of brake
$finish = '03:00'; //finished at 3 after midnight
//the desired result is to print out '7.5'
I used to have following formula in MS Excel which worked great:
=IF(D12>=F12,((F12+1)-D12-E12)*24,(F12-D12-E12)*24) '7.5 worked hours
where
D12 - Start time '19:00
F12 - Finish time '03:00
E12 - Brake time '00:30
I tried to play with strtotime() with no luck. My PHP version is 5.4.45. Please help
To provide a solution that doesn't require as much mathematics or parsing of the time values.
Assuming the day is not known, we can also account for the offset of the finish time and start time, when the start time is late at night.
Example: https://3v4l.org/FsRbT
$start = '07:00'; //started at 7 after midnight
$break = '01:30'; //1 hour and 30 minutes of brake
$finish = '15:00'; //finished at 3 afternoon
//create the start and end date objects
$startDate = \DateTime::createFromFormat('H:i', $start);
$endDate = \DateTime::createFromFormat('H:i', $finish);
if ($endDate < $startDate) {
//end date is in the past, adjust to the next day
//this is only needed since the day the time was worked is not known
$endDate->add(new \DateInterval('PT24H'));
}
//determine the number of hours and minutes during the break
$breakPeriod = new \DateInterval(vsprintf('PT%sH%sM', explode(':', $break)));
//increase the start date by the amount of time taken during the break period
$startDate->add($breakPeriod);
//determine how many minutes are between the start and end dates
$minutes = new \DateInterval('PT1M');
$datePeriods = new \DatePeriod($startDate, $minutes, $endDate);
//count the number of minute date periods
$minutesWorked = iterator_count($datePeriods);
//divide the number of minutes worked by 60 to display the fractional hours
var_dump($minutesWorked / 60); //6.5
This will work with any time values within a 24 hour period 00:00 - 23:59. If the day the times were worked are known, the script can be modified to allow for the day to be given and provide more precise timing.
To do this, convert you string times into a unix timestamp. This is an integer number of seconds since the unix epoch (00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970, minus the number of leap seconds that have taken place since then). Do your math, then use the Date() function to format it back into your starting format:
<?php
$start = '19:00'; //started late afternoon
$break = '00:30'; //30 minutes of brake
$finish = '03:00'; //finished at 3 after midnight
//get the number of seconds for which we took a $break
//do this by converting break to unix timestamp, then extracting the hour and multiplying by 360
//and do the same extracting minutes and multiplying by 60
$breaktime = date("G",strtotime($break))*60*60 + date("i",strtotime($break))*60;
//get start time
$unixstart=strtotime($start);
//get finish time. Add a day if finish is tomorrow
if (strtotime($finish) < $unixstart) {
$unixfinish = strtotime('+1 day', strtotime($finish));
} else {
$unixfinish = strtotime($finish);
}
//figure out time worked
$timeworked = ($unixfinish - $unixstart - $breaktime) / 3600;
echo $timeworked;
?>
Another way, using DateTime. Basically, create 2 DateTime objects with the times of start and finish. To the start time, subtract the brake time, and the subtract from the result the end time.
You need to split the brake time in order to use modify().
<?php
$start = '07:00'; //started at 7 after midnight
$brake = '01:30'; //1 hour and 30 minutes of brake
$brakeBits = explode(":", $brake);
$finish = '15:00'; //finished at 3 afternoon
$startDate = \DateTime::createFromFormat("!H:i", $start);
$startDate->modify($brakeBits[0]." hour ".$brakeBits[1]." minutes");
$endDate = \DateTime::createFromFormat("!H:i", $finish);
$diff = $startDate->diff($endDate);
echo $diff->format("%r%H:%I"); // 06:30
Demo

PHP date interval - wrong month difference

Have a look at this code:
$first = DateTime::createFromFormat('Y-m', '2001-07');
$last = DateTime::createFromFormat('Y-m', '1998-06');
$interval = $first->diff($last);
echo "m diff: ".$interval->m." y diff: ".$interval->y."\n";
The output is m diff: 0 y diff: 3
Why does it return a wrong month difference?
Interesting that if I change dates as '2001-08' and '1998-07', it returns a correct month interval ==1.
Thanks!
PHP DateTime doesn't handle incomplete datetimes.
DateTime::createFromFormat('Y-m', '2011-07') gives a DateTime that has a year of 2011, a month of 7, and a day, hour, minute and second taken from the current time (at the moment I write this, 2011-07-31 18:05:47.
Likewise, DateTime::createFromFormat('Y-m', '1998-06') gives a DateTime that has a year of 1998, a month of 6, and a day, hour, minute, and second taken from the current time. Since June 31st is a nonexistent date, the result is 1998-07-01 18:05:47 (31 days after the day before June 1st).
The difference between those two dates is then 3 years, 0 months, and 30 days.
In your example of 2001-08 and 1998-07, both months happen to have a 31st day, so the math comes out correctly. This bug is a difficult one to pin down, because it depends on the date that the code is run even though it doesn't obviously appear to.
You could probably fix your code by using a format of "Y-m-d H:i:s" and appending "-01 00:00:00" to each date you pass to createFromFormat, which will anchor the DateTime you get back to the beginning of the month.
I know this is old, maybe this may help someone out there:
$first = DateTime::createFromFormat('Y-m', '2001-07');
$last = DateTime::createFromFormat('Y-m', '1998-06');
$interval = $first->diff($last);
$num_months = (($interval->y) * 12) + ($interval->m);
Explanation : convert $interval->y which is the year to months by multiplying it by 12 and add the succeeding months which is $interval->m

Bizzare PHP behaviour calculating time differences, only on 6th and 7th September, 2013

I'm trying to calculate the difference in days between two dates. I'm getting bizzare behaviour - I've narrowed it down to 6th and 7th October, 2013, as you can see below. Whenever the date range spans those dates, the calculation is a day out.
// WRONG! current year - 2013
$datediff = strtotime('2013-10-07') - strtotime('2013-10-06');
$startToEndDays = floor($datediff/(60*60*24));
print_r($startToEndDays); // Outputs 0 - should output 1
// RIGHT! next year - 2014
$datediff = strtotime('2014-10-07') - strtotime('2014-10-06');
$startToEndDays = floor($datediff/(60*60*24));
print_r($startToEndDays); // Outputs 1 - correct
Any idea what could be the issue here?
haha OK, it turns out 6th/7th October 2013 is when daylight savings starts in Sydney, Australia. So, the number of hours between those dates is calculated (correctly) as 23. But, 23 hrs is not quite a day.
If you're using PHP 5.3+, then this is how you should calculate the difference between dates in days, to save yourself any daylight savings headaches:
$startDate = new DateTime('2013-10-07');
$endDate = new DateTime('2013-10-06');
$interval = $startDate->diff($endDate);
$days = $interval->days;

Categories