On one project, I have an internal calculation of times.
The days since the launch are simply enumerated:
2009/10/19: launch day
2009/10/20: day 1
2009/10/21: day 2
etc.
Now I would like to have a function which gives me the current day of the internal calculation of times. E.g. "day 129" on one day in 2010.
But it is important to have this accuracy:
2009/10/20 00:00:01 => day 1
2009/10/20 23:59:59 => day 1
2009/10/21 00:00:01 => day 2
I built the following function but it doesn't have that accuracy. Why not? Can you improve it?
function date2daycount($timestamp) {
$launchDay = 1255903200-3600*24; // launch (2009/10/19 00:00:00)
$difference = floor(($timestamp-$launchDay)/86400); // days after launch
return $difference;
}
Thanks in advance!
function date2daycount($timestamp) {
$launchDay = strtotime('19 October 2009'); // launch (2009/10/19 00:00:00)
$difference = floor(($timestamp-$launchDay)/86400); // days after launch
return $difference+1;
}
Related
I have a problem with php that i don't really know how to solve. I have an array full of unix timestamps coming from a mysql query.
These timestamps are events that repeat every week ( For example, every Tuesday and Thursday ). They can repeat various days or just one.
Knowing the days that repeat, which day will be the next one.
For example:
In the Array I have :
1595289600 --> 2020/07/21 (Tuesday)
1595116800 --> 2020/07/19 (Sunday)
Today we are at 1595376000 (Wednesday) , so it should return 1595116800 + 604800 (Sunday).
In 5 days ( next monday) it should return 1595289600 + 604800 = 1595721600 (First tuesday + one week )
in one week (next Wednesday) , it should return the next Sunday (2020/08/02 ): 1596326400
And so on...
Thank you!
For every timestamp you have - calculate next timestamp (add a week) until it is after current timestamp. Then return lowest from those as that one will be the closest to now (but also in the future).
So lets say it is 2020-07-22 Wednesday.
Your 2020-07-21 Tuesday is in the past, so add a week: 2020-07-28 Tuesday - its in the future, so its our candidate.
Your 2020-07-19 Sunday is also in the past, so add a week: 2020-07-26 Sunday - its in the future so its out second candidate.
Now pick lower from 2 candidates: 2020-07-26 Sunday.
If the dates are more in the past then you will need more a week to them more times.
Something like this:
<?php
// those are your timestamps: $timestamps = [1595289600, 1595116800];
// $time is optional int for when you want to perform the calculation. defaults to current timestamp
function nextOccurence(array $timestamps, $time = null) {
$now = $time ?? time();
$nextTimestamps = [];
foreach ($timestamps as $timestamp) {
while ($timestamp < $now) {
$timestamp += 604800;
}
$nextTimestamps[] = $timestamp;
}
return min($nextTimestamps);
}
I have a database of events that are both "static" (on a specific day) and "recurring" (starting on a specific day, but set to be "recurring" either every week or every other week). I understand that there needs to be intervals of 7 and 14, but I don't know how to get to that point to find a date > today and spit it out.
so example;
I want to find the next upcoming recurring events and spit out their relevant dates. Side note: the data I'm stuck working with is in strings (I know, I know) of Ymd so 20150821 would be Aug 21st 2015.
if today was Aug 21 2015 and there's a recurring event for "Every other Friday" starting on Aug 7, it would be +14 which would get you to today, Friday Aug 21.
But say there was one for "Every Wednesday" starting Aug 19, I'd want to get the date for Wednesday, Aug 26 and spit that out.
This would need to work for infinite dates in the future, with the start dates never changing.
So running the script on Jan 1 2016, I'd need to know that the next "Every Wednesday" was Jan 6 2016.
pseudo code:
if(start_date < today_date) {
// start date is in the past
add recurring_inverval to start_date until result >= today_date
echo result
} elseif(start_date > today_date {
// start date is in the future
echo start_date
}
it's the adding until x that I'm lost at. not sure how to do that within an if statement.
also not sure if that's the best way to go about it. I know PHP can also do complicated strings and convert them to a date. like "Next Saturday"
I know you answered this yourself, however another option is to just use the modulus (remainder after devision) of the current date minus the start date to compute your next date. Here is a quick script to do just that :
<?php
function nextDate($start_date,$interval_days,$output_format){
$start = strtotime($start_date);
$end = strtotime(date('Y-m-d'));
$days_ago = ($end - $start) / 24 / 60 / 60;
if($days_ago < 0)return date($output_format,$start);
$remainder_days = $days_ago % $interval_days;
if($remainder_days > 0){
$new_date_string = "+" . ($interval_days - $remainder_days) . " days";
} else {
$new_date_string = "today";
}
return date($output_format,strtotime($new_date_string));
}
echo nextDate('20151210',14,'Ymd') . "<br />";
echo nextDate('20150808',14,'Ymd') . "<br />";
?>
You also don't want to return an early date if the "start date" is in the distant future. Code updated to prevent that.
solved it myself:
$begin = new DateTime($start_date); // start searching on the start date of the event
$end = new DateTime(date('Ymd')); // end on today's date
$end = $end->modify('+1 month'); // extend search to the next month
$interval = new DateInterval('P'. $freq_math .'D'); // intervals of Plus X Days - uses frequency math of 7 or 14 for every or every other
$daterange = new DatePeriod($begin, $interval, $end);
foreach($daterange as $date) {
if($date->format('Ymd') >= date('Ymd')) {
$next_recurring_date = $date->format('Ymd');
break;
}
}
echo $next_recurring_date;
Basically I am trying to create a basic case logging system and when somebody opens a new case, the case is assigned a priority with a given number of hours. For example priority 1 is 4 hours, 2 is 9 hours, 3 is 36hours and 4 is 63 hours.
Now adding hours onto a time stamp is easy but the catch is I need to take into account working hours which are 08:30 to 17:30 Monday to Friday. So if a case is given a 4 hour priority and the deadline for this falls after 17:30 on a week day then the deadline is extended to the next working day. Basically the deadline is 4 working hours.
Example:
Case created on: 19/05/2014 16:55 - with Priority 1 (4 Hours)
Deadline is now: 20/05/2014 11:55
Make sense?
Another catch is I need to take into account hours On Hold and these two have to be only within working hours. But ill worry about that later.
I am trying to use the modern DateTime class for this as far as possible.
Here is what I have so far, I am struggling with the logic. It works if the deadline is within a day but if I add something like 63 hours it returns back on a Sunday.
Where am I going wrong here? Brain is fried with this :(
<?php
function addRollover($givenDate, $addtime) {
$datetime = new DateTime($givenDate);
$datetime->modify($addtime);
if (in_array($datetime->format('l'), array('Sunday','Saturday')) ||
17 < $datetime->format('G') ||
(17 === $datetime->format('G') && 30 < $datetime->format('G'))
) {
$endofday = clone $datetime;
$endofday->setTime(17,30);
$interval = $endofday->diff($datetime);
$datetime->add(new DateInterval('P1D'));
if (in_array($datetime->format('l'), array('Saturday', 'Sunday'))) {
$datetime->modify('next Monday');
}
$datetime->setTime(8,30);
$datetime->add($interval);
}
return $datetime;
}
//this is returning back 2014-06-29 17:41:00 which is a sunday.
$future = addRollover('2014-06-26 11:41:00', '+63 hours');
echo $future->format('Y-m-d H:i:s');
See it in action: http://3v4l.org/Ac8ro
Here's an explanation of what's supposed to be going on in the function:
First we create a DateTime object representing our starting date/time
We then add the specified amount of time to it (see Supported Date and Time Formats)
We check to see if it is a weekend, after 6PM, or in the 5PM hour with more than 30
minutes passed (e.g. after 5:30PM)
If so we clone our datetime object and set it to 5:30PM
We then get the difference between the end time (5:30PM) and the modified time as a DateInterval object
We then progress to the next day
If the next day is a Saturday we progress to the next day
If the next day is a Sunday we progress to the next day
We then set our time to 8:30AM
We then add our difference between the end time (5:30PM) and the modified time to our datetime object
We return the object from the function
UPDATE 2
Updated the code as per based on suggestions provided
<?php
function addRollover($givenDate, $addtime, $dayStart, $dayEnd, $weekDaysOnly) {
//Break the working day start and end times into hours, minuets
$dayStart = explode(',', $dayStart);
$dayEnd = explode(',', $dayEnd);
//Create required datetime objects and hours interval
$datetime = new DateTime($givenDate);
$endofday = clone $datetime;
$endofday->setTime($dayEnd[0], $dayEnd[1]); //set end of working day time
$interval = 'PT'.$addtime.'H';
//Add hours onto initial given date
$datetime->add(new DateInterval($interval));
//if initial date + hours is after the end of working day
if($datetime > $endofday)
{
//get the difference between the initial date + interval and the end of working day in seconds
$seconds = $datetime->getTimestamp()- $endofday->getTimestamp();
//Loop to next day
while(true)
{
$endofday->add(new DateInterval('PT24H'));//Loop to next day by adding 24hrs
$nextDay = $endofday->setTime($dayStart[0], $dayStart[1]);//Set day to working day start time
//If the next day is on a weekend and the week day only param is true continue to add days
if(in_array($nextDay->format('l'), array('Sunday','Saturday')) && $weekDaysOnly)
{
continue;
}
else //If not a weekend
{
$tmpDate = clone $nextDay;
$tmpDate->setTime($dayEnd[0], $dayEnd[1]);//clone the next day and set time to working day end time
$nextDay->add(new DateInterval('PT'.$seconds.'S')); //add the seconds onto the next day
//if the next day time is later than the end of the working day continue loop
if($nextDay > $tmpDate)
{
$seconds = $nextDay->getTimestamp()-$tmpDate->getTimestamp();
$endofday = clone $tmpDate;
$endofday->setTime($dayStart[0], $dayStart[1]);
}
else //else return the new date.
{
return $endofday;
}
}
}
}
return $datetime;
}
$currentTime = '2014-06-27 08:30:00';
$dayStart = '8,30';
$dayEnd = '17,30';
$future = addRollover($currentTime, 65, $dayStart, $dayEnd, true);
echo "Results: </br>";
echo $future->format('Y-m-d H:i:s').'</br>';
I am creating an application that charges a client based on time usage of a service. The problem is that the services can have double charge for a pre-specified time period of the day.
So let's say we have a service for printing documents and the charge for using the printer is 5€ per hour and 10€ between 23:00 and 02:00 in the morning. Also a client can rent the printer for as much time as he likes. This can be from 1 minute to months or even years.
Now the specific problem:
Let's say a client comes in my office to rent the printer for 55 hours. Also the rent starts at 20:00 at night.
So the charge must be for 43 hours in single charge and for 12 hours in double charge. Here are two example images:
Now, let me give you some extra info about the hours. In programming, each hour has a timestamp that it is time passed from January 1, 1970 00:00:00 to the time in seconds.
So the date July 05 2012 11:15:40 has the timestamp 1373022940 and the date July 05 2012 11:15:50 has the timestamp 1373022950
In the above example lets say that the first example placed in the date May 1, 2013, so the timestamp for 23:00 will be 1367449200 and the time stamp for three days later at the 02:00 the morning is 1367546400
Now the question:
Is there a way to extract the time duration of the double charged hours from a time frame? If so, what is the process?
Of course there is. You just need to count the interval between dates.
Let's say someone started using service since 8:00 and ended in 16:00.
Price from 8:00 - 16:00 = 2$
Price from 16:00 - 8:00 = 1$
So you need to convert the start of usage time and end of usage time to timestamp
date_default_timezone_set('UTC');
$day_start = '2011-06-22';
$day_end = '2011-06-22';
$start_usage = strtotime($day_start.' 8:00');
$end_usage = strtotime($day_end.' 17:00');
$price_low_rate = 1; //price for using service 16-8
$price_high_rate = 2; // price for using service since 8-16
$fee_for_eight_sixteen = 0; // total price for using service since 8-16
$fee_for_sixteen_eight = 0; // total price for using service 16-8
if($end_usage >strtotime($day_start.' 16:01'))
{
$fee_for_sixteen_eight = ($end_usage - strtotime($day_end.' 16:00'))/3600 * $price_low_rate;
}
if($start_usage >= strtotime($day_start.' 8:00'))
{
$fee_for_eight_sixteen = (strtotime($day_end.' 16:00') - $start_usage)/3600 * $price_high_rate;
}
echo $fee_for_eight_sixteen.' - '.$fee_for_sixteen_eight;
I've tested it and it works. Hope it helps.
Haven't tested this, but I hope it gets you on the right track:
<?php
$price = 0;
$start_timestamp = 1367449200;
$end_timestamp = 1367546400;
$start_time_of_day = 1367449200 % (24*60*60); // Number of seconds from start of the day
$end_time_of_day = 1367546400 % (24*60*60); // Number of seconds from start of the day
// How much time the time period spends in the first day (in seconds)
$first_day_time = (24*60*60) - $start_time_of_day;
// How much time the time period spends in the last day (in seconds)
$last_day_time = (24*60*60) - $end_time_of_day;
$full_days_time = $end_timestamp + $last_day_time - ($start_timestamp + $first_day_time);
$full_days = round($full_days_time/(24*60*60));
// You can calculate by hand how much one full 24-hour day from 00:00 to 00:00 costs
$price += $full_days * (2*10 + 21*5 + 1*10);
// so now the difficulty is the pieces of time on the first day and the last day.
$expensive_time = 0; // Expensive time spent on the first and last day
$cheap_time = 0;
if ($start_time_of_day<2*60*60)
{
// Renting starts before 02:00
$expensive_time += 2*60*60 - $start_time_of_day;
$cheap_time += 21*60*60; // Full 21 hours of cheap time
$expensive_time += 1*60*60; // 1 hour of expensive time from 23:00 to midnight
}
elseif ($start_time_of_day<23*60*60)
{
// Renting starts after 02:00 and before 23:00
$cheap_time += 23*60*60 - $start_time_of_day;
$expensive_time += 1*60*60; // 1 hour of expensive time from 23:00 to midnight
}
else
{
// Renting starts after 23:00
$expensive_time += 24*60*60 - $start_time_of_day;
}
// !! Use a similar strategy for the $end_time_of_day here
$price += ceil($expensive_time/60/60) * 10;
$price += ceil($cheap_time/60/60) * 5;
echo $price." euro";
?>
I have a scenario in which the user selects a time and day (or multiple days) and that value must be converted to whatever that day and time would be in UTC time. I have the gmt offset amount for each user (the users set it when they signup). For instance:
A user in the eastern timezone selects:
3:15 pm, Monday, Tuesday, Friday
I need to know what time and days that information would be in UTC time. The solution has to take into situations such Monday in one timezone can be a different day in UTC time. Also, if the time can be converted to 24 hour format, that would be a plus.
For the sake of clarity, something along the lines of an array should be returned such as:
Array('<3:15 pm eastern adjusted for utc>', '<Monday adjusted for UTC>', '<Tuesday adjusted for UTC>', '<Friday adjusted for UTC>');
I don't need the result to be directly formatted into an array like that - that's just the end goal.
I am guessing it involves using strtotime, but I just can't quite my finger out how to go about it.
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
The result will be a timestamp, here's an example:
$input_time = "3:15PM 14th March";
$time_adjustment = +3;
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
echo date("H:i:s l jS F", $timestamp);
// 16:15:00 Monday 14th March
EDIT: kept forgetting little things, that should be working perfectly now.
Made a function to do the job:
<?
/*
* The function week_times() converts a a time and a set of days into an array of week times. Week times are how many seconds into the week
* the given time is. The $offset arguement is the users offset from GMT time, which will serve as the approximation to their
* offset from UTC time
*/
// If server time is not already set for UTC, uncomment the following line
//date_default_timezone_set('UTC');
function week_times($hours, $minutes, $days, $offset)
{
$timeUTC = time(); // Retrieve server time
$hours += $offset; // Add offset to user time to make it UTC time
if($hours > 24) // Time is more than than 24 hours. Increment all days by 1
{
$dayOffset = 1;
$hours -= 24; // Find out what the equivelant time would be for the next day
}
else if($hours < 0) // Time is less than 0 hours. Decrement all days by 1
{
$dayOffset = -1;
$hours += 24; // Find out what the equivelant time would be for the prior day
}
$return = Array(); // Times to return
foreach($days as $k => $v) // Iterate through each day and find out the week time
{
$days[$k] += $dayOffset;
// Ensure that day has a value from 0 - 6 (0 = Sunday, 1 = Monday, .... 6 = Saturday)
if($days[$k] > 6) { $days[$k] = 0; } else if($days[$k] < 0) { $days[$k] = 6; }
$days[$k] *= 1440; // Find out how many minutes into the week this day is
$days[$k] += ($hours*60) + $minutes; // Find out how many minutes into the day this time is
}
return $days;
}
?>