Milliseconds compare in php - php

$date1 = "2017-04-13 09:09:80:300"
$date2 = "2017-04-13 09:09:80:400"
how can I check if the date2 is more or less 100 milliseconds then $date 1 in and false if not (101 - more or less)

Your question, while deceptively appearing simple, is actually fairly ugly, because it is the case that PHP's strtotime() function truncates milliseconds from a timestamp. Actually, it won't even correctly process the timestamps $date1 and $date2 which you have in your question. One workaround is to trim off the millisecond portion of the timestamp, use strtotime() to get milliseconds since the epoch, then use a regex to obtain and add the millisecond portion to this amount.
$date1 = "2017-04-13 09:09:40:300";
$date2 = "2017-04-13 09:09:40:400";
preg_match('/^.+:(\d+)$/i', $date1, $matches);
$millis1 = $matches[1];
$ts1 = strtotime(substr($date1, 0, 18))*1000 + $millis1;
preg_match('/^.+:(\d+)$/i', $date2, $matches);
$millis2 = $matches[1];
$ts2 = strtotime(substr($date2, 0, 18))*1000 + $millis2;
if (abs($ts1 - $ts2) < 100) {
echo "within 100 millseconds";
}
else {
echo "not within 100 millseconds";
}
Demo here:
Rextester

If you get your time in such format (I changed 09:09:80 to 09:09:40 as it was incorrect format)
$date1 = "2017-04-13 09:09:40:300"
$date2 = "2017-04-13 09:09:40:400"
create custom function since strtotime doesn't support ms
function myDateToMs($str) {
list($ms, $date) = array_map('strrev', explode(":", strrev($str), 2));
$ts = strtotime($date);
if ($ts === false) {
throw new \InvalidArgumentException("Wrong date format");
}
return $ts * 1000 + $ms;
}
now just check does difference is less than 100
$lessOrEqual100 = abs(myDateToMs($date1) - myDateToMs($date2)) <= 100;

According to the php manual for strtotime fractions of a second are allowed, although currently ignored by the strtotime function.
This means you could express your dates like this 2017-04-13 09:00:20.100 to have them parsed by strtotime without error (keeping them futureproofed) and then use a custom function to compare just the millisecond portion of the dates if the timestamps are the same
The below function will return true if the dates are within 100 milliseconds, false otherwise. You can pass in the amount to compare them by as an argument.
<?php
date_default_timezone_set ( "UTC" );
$date1 = "2017-04-13 09:00:20.100";
$date2 = "2017-04-13 09:00:20.300";
// pass date1, date2 and the amount to compare them by
$res = compareMilliseconds($date1,$date2,100);
var_dump($res);
function compareMilliseconds($date1,$date2,$compare_amount){
if(strtotime($date1) == strtotime($date2)){
list($throw,$milliseond1) = explode('.',$date1);
list($throw,$milliseond2) = explode('.',$date2);
return ( ($milliseond2 - $milliseond1) < $compare_amount);
}
}
?>

PHP 7.1 lets you do it with DateTime objects...
Be sure to test all other answers with a change of day as a true indicator of a successful process.
Demo
Code:
$dt1 = DateTime::createFromFormat('Y-m-d H:i:s:u e', "2017-04-14 0:00:00:000 UTC");
$dt2 = DateTime::createFromFormat('Y-m-d H:i:s:u e', "2017-04-13 23:59:59:999 UTC");
var_export($dt1->format('Y-m-d H:i:s:u'));
echo "\n";
var_export($dt2->format('Y-m-d H:i:s:u'));
echo "\n";
//var_export($dt1->diff($dt2));
echo "\n";
$diff=$dt1->diff($dt2);
// cast $diff as an array so array_intersect_assoc() can be used
if(sizeof(array_intersect_assoc(['y'=>0,'m'=>0,'d'=>0,'h'=>0,'i'=>0],(array)$diff))==5){
// years, months, days, hours, and minutes are all 0
var_export($micro=round(abs($diff->s+$diff->f),3));
// combine seconds with microseconds then test
echo "\n";
if($micro>.1){
echo "larger than .1";
}else{
echo "less than or equal to .1";
}
}else{
echo "too large by units larger than seconds";
}
Outputs:
'2017-04-14 00:00:00:000000'
'2017-04-13 23:59:59:999000'
0.001
less than or equal to .1

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

Comparing DateTime Not Working

I created two datetime objects where $date1 = 09/02/2013 and $date2 = 03/02/2014
When I run the following code:
if ($date2 < $date1)
{
echo "hi";
}
for some reason it echos "hi" although $date2 is clearly greater than $date1. How am i supposed to compare these two dates? Please help!
<?php
$date1 = new DateTime ('2013-12-25');
$date2 = new DateTime ('2014-11-24');
if ($date1 > $date2) {
echo ('date1 is greater than date2');
}
else {
echo ('date2 is greater than date1');
}
use like below with function http://php.net/manual/en/function.strtotime.php
if (strtotime($date2 ) < strtotime($date1))
{
echo "hi";
}
hope this will sure help you.
That could work in JavaScript, but in PHP it will not :P
However, you could calculate an interval between dates.
$interval = $date1->diff($date2);
if ($interval->invert){ //1 if negative and 0 if positive
// $date2 has a bigger time value
} else {
// $date1 has a bigger time value
}

How to compare two time in PHP

I had two times in the format like 7:30:00 and 22:30:00 stored in the variables $resttimefrom and $resttimeto respectively.
I want to check whether the current time is between these two values. I am checking this with the code
$time = date("G:i:s");
if ($time > $resttimefrom and $time < $resttimeto ){
$stat = "open";
} else {
$stat = "close";
}
But I am always getting the $stat as Close. What may cause that?
you can try using strtotime
$st_time = strtotime($resttimefrom);
$end_time = strtotime($resttimeto);
$cur_time = strtotime(now);
then check
if($st_time < $cur_time && $end_time > $cur_time)
{
echo "WE ARE CLOSE NOW !!";
}
else{
echo "WE ARE OPEN NOW !!";
}
i hope this may help you..
A simple yet smart way to do this is to remove the ':' from your dates.
$resttimefrom = 73000;
$resttimeto = 223000;
$currentTime = (int) date('Gis');
if ($currentTime > $resttimefrom && $currentTime < $resttimeto )
{
$stat="open";
}
else
{
$stat="close";
}
$today = date("m-d-y ");
$now = date("m-d-y G:i:s");
if (strtotime($today . $resttimefrom) < $now && $now > strtotime($today . $resttimeto)) {
$stat = 'open';
else
$stat = 'close
Try reformatting them into something that you can compare like that. For example, numbers:
$resttimefrom = mktime(7,30,0);
$resttimeto = mktime(22,30,0);
$time = mktime(date('H'),date('i'),date('s'));
You are comparing strings.
Convert the Time Strings to timestamps with strtotime().
Then compare against time().
Just convert your dates to a Unix Timestamp, compare them, you have your results! It might look something like this:
$time =date("G:i:s");
$time1 = strtotime($time);
$resttimefrom1 = strtotime($resttimefrom );
$resttimeto1 = strtotime($resttimeto );
if ($time1 >$resttimefrom and $time1 <$resttimeto)
{
$stat="open";
}
else
{
$stat="close";
}
The date function returns a string, so the comparison you're making would be a string comparison - so 7:30 would be more than 22:30
It would be much better to use mktime, which will return a Unix timestamp value (integer) so it would make for a better comparison
$currentTime = mktime();
$resttimefrom = mktime(hour,min,second);
http://php.net/mktime
The trick to manipulating and comparing dates and times in PHP is to store date/time values in an integer variable and to use the mktime(), date() and strtotime() functions. The integer repesentation of a date/time is the number of seconds since midnight, 1970-Jan-1, which is referred to as the 'epoch'. Once your date/time is in integer form you'll be able to efficiently compare it to other dates that are also in integer form.
Of course since you'll most likely be receiving date/time values from page requests and database select queries you'll need to convert your date/time string into an integer before you can do any comparison or arithmetic.
Assuming you are sure that the $resttimefrom and $resttimeto variables contain properly formatted time you can use the strtotime() function to convert your string time into an integer. strtotime() takes a string that is formatted as a date and converts it to the number of seconds since epoch.
$time_from = strtotime($resttimefrom);
$time_to = strtotime($resttimeto);
Side note: strtotime() always returns a full date in integer form. If your string doesn't have a date, only a time, strtotime() return today's date along with the time you gave in the string. This is not important to you, though, because the two dates returned by strtotime() will have the same date and comparing the two variables will have the desired effect of comparing the two times as the dates cancel each other out.
When you compare the two integers keep in mind that the earlier the date/time is, the smaller its integer value will be. So if you want to see if $time_from is earlier than $time_to, you would have this:
if ($time_from < $time_to)
{
// $time_from is ealier than $time_to
}
Now to compare a date/time with the current system date/time, just use mktime() with no parameters to represent the current date/time:
if ($time_from < mktime())
{
// $time_from is in the past
}
$firstTime = '1:07';
$secondTime = '3:01';
list($firstMinutes, $firstSeconds) = explode(':', $firstTime);
list($secondMinutes, $secondSeconds) = explode(':', $secondTime);
$firstSeconds += ($firstMinutes * 60);
$secondSeconds += ($secondMinutes * 60);
$difference = $secondSeconds - $firstSeconds;
$Time1 = date_parse($time);
$seconds1 = $Time1['hour'] * 3600 + $Time1['minute'] * 60 + $Time1['second'];
$Time2 = date_parse($current_time);
$seconds2 = Time2['hour'] * 3600 + Time2['minute'] * 60 + Time2['second'];
$actula_time = $seconds1 - $seconds2;
echo floor($actula_time / 3600) .":". floor(($actula_time / 60)%60) .":". $actula_time%60;
As Col. Shrapnel Said i am doing by converting all the time in to seconds and then compare it with current time's total seconds

Checking if mySql datetime is older then 1 day from php now()

I have a record returned from MySQL that has a datetime field. What I want to do is take this value and see if it is older then 24 hours, I presume using PHP's time() to get the current time.
At the moment if I echo them out I get:
1276954824 this is php's time()
2010-06-19 09:39:23 this is the MySQL datetime
I presume the top one is a unix time? Have been playing around with strtotime but with not much success..
ANy help welcome!
No success?
echo strtotime("2010-06-19 09:39:23");
gives me
1276940363
(mktime(9, 39, 23, 6, 19, 2010) gives the same time, so the parsing works correctly)
To get the differences in seconds, you can substract the timestamps, e.g.
$diff = time() - strtotime("2010-06-19 09:39:23");
If the differences is larger than 86400 (60*60*24) seconds, then the timestamps are more than one day apart:
if(time() - strtotime("2010-06-19 09:39:23") > 60*60*24) {
// timestamp is older than one day
}
You can also do:
SELECT * FROM my_table WHERE timestamp < NOW() - INTERVAL 1 DAY;
Why are you mixing PHP times and MySQL times?
Instead, do the comparison directly in MySQL:
To get the current date/time in MySQL use the NOW() function. You can compare, for example, 2010-06-19 09:39:23' < DATE_SUB(NOW(), INTERVAL 1 DAY)
This would check to see if the given date (presumably in a column) is older than 24 hours.
If it's absolutely necessary to convert a MySQL timestamp to a UNIX timestamp, you can use MySQL's UNIX_TIMESTAMP() function to do so.
I wrote a function, by which you can determine if the first given date is one day or n days bigger or smaller than the second given date.
$date1 = "2013/03/01";
$date2 = "2013/03/01";
$sign = "-";
$diff = 1;
$result = isDaysSmallerBigger($date1, $date2, $sign, $diff);
var_dump($result);
/**
* Note: this function is only supported in php 5.3 or above
* 1. If $date1 - $date2 = $sign $diff days, return true;
* 2. If $date1 equals $date2 and $diff euqals 0, whether $sign is "+" or "-", return true
* 3. Else return false;
* #param unknown_type $date1
* #param unknown_type $date2
* #param string $sign: "-": $date1 < $date2; "+": $date1 > $date2;
* Besides if $diff is 0, then both "-" and "+" means $date1 === $date2;
* #param integer $diff: date difference between two given dates
*/
function isDaysSmallerBigger($date1, $date2, $sign, $diff) {
$dateTime1 = new DateTime($date1);
$dateTime2 = new DateTime($date2);
$interval = $dateTime2->diff($dateTime1);
$dayDiff = $interval->format('%a');
$diffSign = $interval->format('%R');
if((int)$dayDiff === (int)$diff) {
// Correct date difference
if((int)$diff !== 0) {
// Day difference is not 0
if($diffSign === $sign) {
return true;
} else {
return false;
}
} else if((int)$diff === 0) {
// Day difference is 0, then both given "+" and "-" return true
return true;
}
} else {
// Incorrect date difference
return false;
}
}

Categories