How to find range diff 'datetime' and 'time'? - php

I want to find a range combining both data, that data has datetime and time data types, but datetime must ignore the time.
<?php
function test_duration($start_date, $end_date, $start_time, $end_time) {
$timeInterval = '-';
if(!empty($start_time) && !empty($end_time)) {
$timeStart = new DateTime($start_date->format('Y-m-d').' '.$start_time->format('H:i:s'));
$timeEnd = new DateTime($end_date->format('Y-m-d').' '.$end_time->format('H:i:s'));
$timeInterval = $timeStart->diff($timeEnd)->format('%H:%I:%s');
}
return $timeInterval;
}
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
echo test_duration($start_date, $end_date, $start_time, $end_time);
?>
so the formula is like this:
range start ==> $start_date (just date) + $start_time
range end ==> $end_date (just date) + $end_time
range start - range end
From the code above it should produce a duration of 5 seconds.
Do you have any solution to fix my code above?

The time can easily be removed from the date with strstr. Then the pure date can be combined with the new time. strtotime is well suited when only seconds are to be determined.
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
$strStart = strstr($start_date, ' ', true).' '.$start_time;
$strEnd = strstr($end_date, ' ', true).' '.$end_time;
$seconds = strtotime($strEnd) - strtotime($strStart); // int(5)

Time is time, date is date, you shouldn't mix them, so let's say
$start_date = '2022-09-15';
$start_time = '13:00:00';
$end_date = '2022-09-15';
$end_time = '14:00:00';
print strtotime($end_date) + strtotime($end_time) - strtotime($start_date) - strtotime($start_time);
You'll get 3600 seconds

If you know the date is in a fixed format can't you just explode the string on the central space like this?
<?php
function test_duration($start_date, $end_date, $start_time, $end_time) {
$timeInterval = '-';
if(!empty($start_time) && !empty($end_time)) {
$startDateOnly=explode(' ',$start_date)[0];
$endDateOnly=explode(' ', $end_date)[0];
$timeStart = date_create_from_format('Y-m-d H:i:s', $startDateOnly." ".$start_time);
$timeEnd = date_create_from_format('Y-m-d H:i:s', $endDateOnly." ".$end_time);
$timeInterval = $timeStart->diff($timeEnd)->format('%h:%i:%s');
}
return $timeInterval;
}
$start_date = '2022-09-15 01:01:01';
$end_date = '2022-09-15 02:02:02';
$start_time = '14:48:40';
$end_time = '14:48:45';
echo test_duration($start_date, $end_date, $start_time, $end_time);
?>

Your start is quite good, the use of DateTime class is one of the ways to solve your issue. The idea here can be illustrated as follows:
create a DateTime object from the starting date and then alter its time (hours, minutes and seconds) based on the starting time you supply.
do the same thing as the first step but for the ending date so we'll create a DateTime object from the ending date and then alter its time based on the ending time.
return the difference between the two dates in seconds:
to do so we will get the timestamps from both dates
make a simple subtraction of th two timestamps
return the result. We may return the absolute value here to always get a positive number for the case when the starting date is greater than the ending date (not required but that can be seen as an improvement).
Here's a live demo too
$startDate = '2022-09-15 01:01:01';
$endDate = '2022-09-15 02:02:02';
$startTime = '14:48:40';
$endTime = '14:48:45';
function diffInSeconds($startDate, $endDate, $startTime, $endTime)
{
// create a DateTime object based on $startingDate and then alter the time to use the $startingTime instead
$startDate = (new DateTime($startDate))->setTime(
($startTime = explode(':', $startTime))[0],
$startTime[1],
$startTime[2]
);
// create a DateTime object based on $endingDate and then alter the time to use the $endingTime instead
$endDate = (new DateTime($endDate))->setTime(
($endTime = explode(':', $endTime))[0],
$endTime[1],
$endTime[2]
);
// return the difference in seconds which will always be positive thanks to the "abs" function
return abs($endDate->getTimestamp() - $startDate->getTimestamp());
}
// run...
echo diffInSeconds($startDate, $endDate, $startTime, $endTime); // prints: 5
the above is code somehow primitive, it doesn't have any checks on whether the date/times are correct or not also it expects the times to be in the following format "HH:MM:SS".
Anyway, i strongly recommend looking at more modern utilities, especially the Carbon library which makes working with dates and times in PHP a piece of cake.
Learn more about DateTime objects on php.net.

Related

how to get Random date between 2 date values using php? [duplicate]

I am coding an application where i need to assign random date between two fixed timestamps
how i can achieve this using php i've searched first but only found the answer for Java not php
for example :
$string = randomdate(1262055681,1262055681);
PHP has the rand() function:
$int= rand(1262055681,1262055681);
It also has mt_rand(), which is generally purported to have better randomness in the results:
$int= mt_rand(1262055681,1262055681);
To turn a timestamp into a string, you can use date(), ie:
$string = date("Y-m-d H:i:s",$int);
If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.
A quick PHP example would be:
// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
// Convert to timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to desired date format
return date('Y-m-d H:i:s', $val);
}
This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.
Another solution using PHP DateTime
$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.
function randomDateInRange(DateTime $start, DateTime $end) {
$randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
$randomDate = new DateTime();
$randomDate->setTimestamp($randomTimestamp);
return $randomDate;
}
You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.
For example, to get a date a random numbers days between now and 30 days out.
echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
Here's another example:
$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;
$daystep = 86400;
$datebetween = abs(($dateend - $datestart) / $daystep);
$randomday = rand(0, $datebetween);
echo "\$randomday: $randomday\n";
echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";
The best way :
$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );
By using carbon and php rand between two dates
$startDate = Carbon::now();
$endDate = Carbon::now()->subDays(7);
$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');
OR
$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');
An other solution where we can use date_format :
/**
* Method to generate random date between two dates
* #param $sStartDate
* #param $sEndDate
* #param string $sFormat
* #return bool|string
*/
function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
// Convert the supplied date to timestamp
$fMin = strtotime($sStartDate);
$fMax = strtotime($sEndDate);
// Generate a random number from the start and end dates
$fVal = mt_rand($fMin, $fMax);
// Convert back to the specified date format
return date($sFormat, $fVal);
}
Source : https://gist.github.com/samcrosoft/6550473
You could use for example :
$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');
The amount of strtotime in here is WAY too high.
For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:
function random_date_in_range( $date1, $date2 ){
if (!is_a($date1, 'DateTime')) {
$date1 = new DateTime( (ctype_digit((string)$date1) ? '#' : '') . $date1);
$date2 = new DateTime( (ctype_digit((string)$date2) ? '#' : '') . $date2);
}
$random_u = random_int($date1->format('U'), $date2->format('U'));
$random_date = new DateTime();
$random_date->setTimestamp($random_u);
return $random_date->format('Y-m-d') .'<br>';
}
Call it any number of ways ...
// timestamps
echo random_date_in_range(157766400,1489686923);
// any date string
echo random_date_in_range('1492-01-01','2050-01-01');
// English textual parsing
echo random_date_in_range('last Sunday','now');
// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);
As is, the function requires date1 <= date2.
i had a same situation before and none of the above answers fix my problem so i
Came with new function
function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
//inspired by
// https://gist.github.com/samcrosoft/6550473
// Convert the supplied date to timestamp
$minDateString = strtotime($startDate);
$maxDateString = strtotime($endDate);
if ($minDateString > $maxDateString)
{
throw new Exception("From Date must be lesser than to date", 1);
}
for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++)
{
$randomDate[] = mt_rand($minDateString, $maxDateString);
}
if (sizeof($randomDate) == 1)
{
$randomDate = date($dateFormat, $randomDate[0]);
return $randomDate;
}elseif (sizeof($randomDate) > 1)
{
foreach ($randomDate as $randomDateKey => $randomDateValue)
{
$randomDatearray[] = date($dateFormat, $randomDateValue);
}
//return $randomDatearray;
return array_values(array_unique($randomDatearray));
}
}
Now the testing Part(Data may change while testing )
$fromDate = '2012-04-02';
$toDate = '2018-07-02';
print_r(randomDate($fromDate,$toDate,1));
result will be
2016-01-25 11:43:22
print_r(randomDate($fromDate,$toDate,1));
array:10 [▼
0 => "2015-08-24 18:38:26"
1 => "2018-01-13 21:12:59"
2 => "2018-06-22 00:18:40"
3 => "2016-09-14 02:38:04"
4 => "2016-03-29 17:51:30"
5 => "2018-03-30 07:28:48"
6 => "2018-06-13 17:57:47"
7 => "2017-09-24 16:00:40"
8 => "2016-12-29 17:32:33"
9 => "2013-09-05 02:56:14"
]
But after the few tests i was thinking about what if the inputs be like
$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';
So the duplicates may occur while generating the large number of dates such as 10,000
so i have added array_unique and this will return only the non duplicates
if you use laravel then it's for you.
\Carbon\Carbon::now()->subDays(rand(0, 90))->format('Y-m-d');
Simplest of all, this small function works for me
I wrote it in a helper class datetime as a static method
/**
* Return date between two dates
*
* #param String $startDate
* #param String $endDate
* #return String
*
* #author Kuldeep Dangi <kuldeepamy#gmail.com>
*/
public static function getRandomDateTime($startDate, $endDate)
{
$randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
return date(self::DATETIME_FORMAT_MYSQL, $randomTime);
}
Pretty good question; needed to generate some random sample data for an app.
You could use the following function with optional arguments to generate random dates:
function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
return $result;
}
sample input:
echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00
echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>';
//1942/Jan/19 00:00 AM
echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January
echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00
echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00
echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00
readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.
Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .
The function accepts:
start date
end date
format: any php accepted format for date or time
timezone: name or offset number
mode: debug, epoch, verbose epoch or verbose
the output in not debug mode is random number according to optional specifications.
tested with PHP 7.x
// Find a randomDate between $startDate and $endDate
function randomDate($startDate, $endDate)
{
// Convert to timetamps
$min = strtotime($startDate);
$max = strtotime($endDate);
// Generate random number using above bounds
$val = rand($min, $max);
// Convert back to date
return Carbon::createFromTimestamp($val);
}
dd($this->randomDate('2014-12-10', Carbon::now()->toString()));
Using carbon
$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);
Full random date and time

PHP: Function to divide the time between two timestamps into equal intervals getting stuck

I have a function where I pass total 5 parameters to it.
$Date1, $Time1, $Date2 and $Time2 and $Interval.
I first form a timestamp1 using Date1Time1, then form a timestamp2 using Date2Time2 , and then I divide these two timestamps into equal intervals of hours and then store into an associative array.
e.g.
$Date1 = 27-03-2016
$Time1 = 18:00
$Date2 = 27-03-2016
$Time2 = 21:00
Now I want to divide this time into equal time intervals of 60 mins, and then want to store into an associative array into below format.
$array = [27-03-2016 => 18:00 , 27-03-2016 => 19:00, 27-03-2016 => 20:00, 27-03-2016 => 21:00]
I have written below function in php. When I run this, the file is getting hanged forever and not responding anything and when I check the server logs then it gives
error: Maximum execution time of 30 seconds exceeded at line
$end_time = date('H-i',strtotime($end_timestamp));
As I am comparatively new to php, I am not able to understand what is going wrong.
function FindTimeSpan (&$Date1,&$Time1,&$Date2,&$Time2,&$Interval)
{
$timespan=array($Date1 => $Time1);
$timestamp1 = strtotime($Date1 . $Time1);
$timestamp2 = strtotime($Date2 . $Time2);
while( $Date1 < $Date2)
{
$start_timestamp = $timestamp1;
$end_timestamp = $timestamp2 . '+' .$Interval;
//Separating Date and Time from a timestamp
$end_date = date('Y-m-d',strtotime($end_timestamp));
$end_time = date('H-i',strtotime($end_timestamp));
//pushing value to an array
$timespan = array_merge($timespan, array($end_date => $end_time));
//setting the start value to the new end value
$timestamp1 = $end_timestamp;
}
echo 'timestamp array' . json_encode($timespan);
}
The problem you encounter is an infinite loop, which is caused by the condition $Date1 < $Date2 . You don't modify any of these two values, so the condition will always be true. Strangely, you don't use the different timestamp values that are modified, but you should.
Concerning that, you should replace $end_timestamp = $timestamp2 . '+' .$Interval; by simply $end_timestamp = $timestamp2 + $Interval ; . Using the single quotes and the point will make PHP think of this as a string operation instead of a mathematical operation. With this and using this loop condition $timestamp1 < $timestamp2, your code should stop.
As said in a comment, your array structure is impossible because you can't assign have the same key multiple times. Instead of this, you should create an array per date and pushing the different times to these arrays.
To do this, you should first fix the way you retrieve the date and time in the loop. In the following code, the call to strtotime is unnecessary as the function date requires a timestamp, so no need to convert this back to a string.
//Separating Date and Time from a timestamp
$end_date = date('Y-m-d',strtotime($end_timestamp));
$end_time = date('H-i',strtotime($end_timestamp));
You should also be consistent, the format used here for the date is not consistent with the format you gave as exemple.
Now as per your suggestions above, I have made few changes in my code as well as the requirement.
I have not decided to use Assoc array.
Instead I will divide the two stamps between equal timeintervals (assuming it is possible).
Then I am doing the simple array push of this string.
Later on once this array is form, I will parse it and take the Date and Time separate.
Now my code is not entering into infinite loop as I am comparing the two timestamps. But now, the issue is it is pushing the first value to the array but all the subsequent values are getting pushed as null
so the output I am getting from the below code is like
array[1459051200,null,null,null,......]
Below is the code
$Date1 = "2016-03-27";
$Time1 = "00:00";
$Date2 = "2016-03-30";
$Time2 = "22:00";
$Interval = '60';
FindTimeSpan ($Date1, $Time1, $Date2, $Time2, $Interval);
function FindTimeSpan (&$Date1,&$Time1,&$Date2,&$Time2,&$Interval)
{
$timestamp1 = strtotime($Date1 . $Time1);
$timespan=array();
array_push($timespan,$timestamp1);
echo 'Value of array timespan' . json_encode($timespan);
$timestamp2 = strtotime($Date2 . $Time2);
while( $timestamp1 < $timestamp2)
{
$start_timestamp = $timestamp1;
$end_timestamp = $timestamp1 + $Interval;
//pushing value to an array
array_push($timespan,$end_timespan);
//
$timestamp1 = $end_timestamp;
}
echo 'timestamp array' . json_encode($timespan);
}

Time To Percent Using PHP

This may sound like a dumb question, but how can I convert the time between two dates to a percent?
I am using this Jquery plugin: http://tinacious.github.io/goalProgress/
The script on page that calculates the percent is:
$('#timerGoal').goalProgress({
goalAmount: 100,
currentAmount: 40,
textBefore: '',
textAfter: '% Completed.'
});
Where it says goalAmount: I'd like that to remain at 100, but where it says currentAmount: 40, I'd somehow like to find the difference in percentage between two days, I know I'd have to set a start date, current date, and end date to find a percentage.
I'm certain part of the code would have to be:
$startDate = '01/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '02/15/2015 12:00:00';
Finding the difference in two dates is fairly easy, but it's the third date thing I cannot grasp, especially to make it a percentage.
Any ideas?
I was thinking something along the lines of:
[Taken from: How to find the difference in days between two dates ]
$daylen = 60*60*24;
$date1 = '2010-03-29';
$date2 = '2009-07-16';
echo (strtotime($date1)-strtotime($date2))/$daylen;
But everything I read on is two dates not three.
Here is what I've come up with.
It's not calculating percentages yet, but it's something to possibly go off of:
$startDate = '08/01/2015 12:00:00';
$currentDate = date('d/M/Y H:i:s');
$endDate = '09/01/2015 12:00:00';
$startDate =str_replace(array(':', '/', ' '), '', $startDate);
$currentDate =str_replace(array(':', '/', ' '), '', $currentDate);
$endDate =str_replace(array(':', '/', ''), ' ', $endDate);
$mainPercent = $endDate - $startDate;
$actualPercent = $endDate - $currentDate;
$displayPercent = $actualPercent/$mainPercent * 100;
echo $displayPercent;
With todays date being 08/07/2015 I am getting 901.2015119993 which is obviously not a percent, but it's a start.
Working Solution:
$startDate = strtotime('08/01/2015 12:00:00');
$currentDate = time(date('d/M/Y H:i:s'));
$endDate = strtotime('09/15/2015 12:00:00');
$dateDivideBy = $endDate - $startDate;
$dateDivide = $currentDate - $startDate;
$divideProduct = $dateDivide / $dateDivideBy;
$datePercent = round($divideProduct * 100);
echo $datePercent;
With this working code and todays date being 08/07/2015 the value of $datePercent is 14.
The difference between two times, by itself, really can't be converted to a percentage. It's just a period of time. In order to figure out what percentage is complete, you would need to know how long the entire goal is supposed to take (an estimated time, I assume.) Then you can figure out the percentage like this:
ElapsedTime / TotalTime * 100
The total time would be End Date - Start Date, and the elapsed time would be now - start date.
Rather than using string functions to manipulate the dates, it would be better to use DateTime functions.
$startDate = '08/01/2015 12:00:00';
$endDate = '09/01/2015 12:00:00';
$startDate = new DateTime($startDate);
$currentDate = new DateTime(); // defaults to now
$endDate = new DateTime($endDate);
$totalTime = $endDate->diff($startDate)->format('%a');
$elapsedTime = $currentDate->diff($startDate)->format('%a');
// diff returns a DateInterval object; calling its format method
// with %a returns the number of days in the interval
$percent = ($elapsedTime / $totalTime) * 100;
I believe this is your desired outcome, where result is the resulting percent difference between start_actual_time and percent_time:
var percent_time= new Date("01/17/2013 11:20");
var start_actual_time = new Date("01/17/2012 11:20");
var end_actual_time = new Date("01/17/2014 11:20");
var range = end_actual_time - start_actual_time;
var diff = end_actual_time - percent_time;
var result = (diff / range)*100;
In this example, start_actual_time and percent_time are 40% different.

Random time and date between 2 date values

I'm trying to write a php script (or line of code) to echo a random time and date between 2 dates, eg
2012-12-24 13:03
which would be between my chosen dates of 1st October 2012 and 1st Jan 2013.
Any ideas how best to do this? Thanks in advance.
Easy :) Just choose 2 random dates, convert to EPOCH, and random between these 2 values :)
EPOCH - The time since 1/1/1970, in seconds.
You can use the strtotime() function to make date-strings turn into epoch time, and the date() function to make it the other way back.
function rand_date($min_date, $max_date) {
/* Gets 2 dates as string, earlier and later date.
Returns date in between them.
*/
$min_epoch = strtotime($min_date);
$max_epoch = strtotime($max_date);
$rand_epoch = rand($min_epoch, $max_epoch);
return date('Y-m-d H:i:s', $rand_epoch);
}
You probably want to define a resolution, for example one minute, or three minutes or 15 seconds or one and a half day or what not. The randomness should be applied on the whole period, I've choosen one minute here for exemplary purposes (there are 132480 minutes in your period).
$start = new Datetime('1st October 2012');
$end = new Datetime('1st Jan 2013');
$interval = new DateInterval('PT1M'); // Resolution: 1 Minute
$period = new DatePeriod($start, $interval, $end);
$random = new RandomIterator($period);
list($result) = iterator_to_array($random, false) ? : [null];
This for example gives:
class DateTime#7 (3) {
public $date =>
string(19) "2012-10-16 02:06:00"
public $timezone_type =>
int(3)
public $timezone =>
string(13) "Europe/Berlin"
}
You can find the RandomIterator here. Without it, it will take a little longer (ca. 1.5 the number of iterations compared to the example above) using:
$count = iterator_count($period);
$random = rand(1, $count);
$limited = new LimitIterator(new IteratorIterator($period), $random - 1, 1);
$limited->rewind();
$result = $limited->current();
I also tried with seconds, but that would take quite long. You probably want first to find a random day (92 days), and then some random time in it.
Also I've run some tests and I could not find any benefit in using DatePeriod so far as long as you're on common resolutions like seconds:
$start = new Datetime('1st October 2012');
$end = new Datetime('1st Jan 2013');
$random = new DateTime('#' . mt_rand($start->getTimestamp(), $end->getTimestamp()));
or minutes:
/**
* #param DateTime $start
* #param DateTime $end
* #param int|DateInterval $resolution in Seconds or as DateInterval
* #return DateTime
*/
$randomTime = function (DateTime $start, DateTime $end, $resolution = 1) {
if ($resolution instanceof DateInterval) {
$interval = $resolution;
$resolution = ($interval->m * 2.62974e6 + $interval->d) * 86400 + $interval->h * 60 + $interval->s;
}
$startValue = floor($start->getTimestamp() / $resolution);
$endValue = ceil($end->getTimestamp() / $resolution);
$random = mt_rand($startValue, $endValue) * $resolution;
return new DateTime('#' . $random);
};
$random = $randomTime($start, $end, 60);
Assuming you want to include October 1st, but not include Jan 1st...
$start = strtotime("2012-10-01 00:00:00");
$end = strtotime("2012-12-31 23:59:59");
$randomDate = date("Y-m-d H:i:s", rand($start, $end));
echo $randomDate;
so crazy it just may worK
function randomDate($start_date, $end_date)
{
//make timetamps
$min = strtotime($start_date);
$max = strtotime($end_date);
//random date
$rand_date = rand($min, $max);
//format it
return date('Y-m-d H:i:s', $rand_date);
}
Here's some code to accomplish this:
$randDate=date('Y-m-d', mt_rand(strtotime('2012-10-01'), strtotime('2013-01-01')));
Okay, here's something
$date_start = strtotime('1 October 2012');
$date_end = strtotime('1 January 2013');
$rand_date = rand($date_start, $date_end);
echo(date('d.m.Y H:i', $rand_date));

Trouble calculating and displaying days left in PHP

I have two variables stored in my database containing the following data:
$date_published = 2012-05-04 00:00:00; //Straight from DB datetime field
$advert_duration = 15;
I want to show an advert for 15 days from the date it was published. To do so I need to work out the time difference.
I have read various places online about calculating time difference and have come up with the below code
In my attempt to work out the equation I can't seem to calculate the differences between $now - the date today, the $date_published and the $advert_duration. I can't get the correct result:
function days_left($date_published, $advert_duration){
$date = new DateTime($date_published);
$now = new DateTime();
$days_elapsed = $date->diff($now)->format("%d");
$days_left = $advert_duration - $days_elapsed;
return $days_left;
}
function getDaysLeft( $date, $duration )
{
// create $date and modify it by $duration
$date = new DateTime( $date );
$date->modify( sprintf( '+%d days', $duration ) );
// calculate the difference
$now = new DateTime();
$daysElapsed = (int) $now->diff( $date )->format( '%a' );
// set to negative value, if modified $date is before $now
if( $date < $now )
{
$daysElapsed = $daysElapsed * -1;
}
return $daysElapsed;
}
var_dump(
getDaysLeft( '2012-05-04 00:00:00', 15 ),
getDaysLeft( '2012-07-04 00:00:00', 15 )
);
If you're fetching your ad from the database, you can simply use a date function to calculate this :
WHERE DATE_SUB(CURDATE(),INTERVAL 15 DAY) >= date
Or you can do this in PHP (you'll get an UNIX timestamp) :
$date = strtotime('+15 days', strtotime($date_published));

Categories