Current time plus one for date validation? - php

I'm having issues with a booking system that i'm trying to customize. It seems that the validation doesn't work on the current date and time if i select the current day.
The validation is a as following.
if (strtotime($str) < time()) {
But that doesn't allow me to book on the current date, even if the time is over current time, not sure if i should add + one to the validation or what. Any ideas would be very helpful.
Here is the full function.
public function _validate_date($str) {
if (strtotime($str) < time()) {
$this->form_validation->set_message('_validate_date', 'Date must be after today, you can only make future reservations!');
return FALSE;
} else {
return TRUE;
}
}

Try the following solution:
$datetime1 = new DateTime($str);
$datetime1->setTime(0, 0, 0);
$datetime2 = new DateTime();
$datetime2->setTime(0, 0, 0);
//get the diff.
$diff = $datetime2->diff($datetime1);
$days = (int) $diff->format("%R%a");
if ($days < 0) {
echo 'past days';
} elseif ($days == 0) {
echo 'today';
} else {
echo 'future days';
}
A working example you can find here: https://3v4l.org/QQ4Pu
Your function with the new solution:
public function _validate_date($str) {
$datetime1 = new DateTime($str);
$datetime1->setTime(0, 0, 0);
$datetime2 = new DateTime();
$datetime2->setTime(0, 0, 0);
//get the diff.
$diff = $datetime2->diff($datetime1);
$days = (int) $diff->format("%R%a");
if ($days <= 0) {
$this->form_validation->set_message('_validate_date', 'Date must be after today, you can only make future reservations!');
return false;
} else {
return true;
}
}
And a working example of your function: https://3v4l.org/HPTVF

If you want check, that current time is not higher current date, try this:
if (strtotime($str) < strtotime(date('Y-m-d 23:59:59')) {

Related

php - if date older than 6 months ago

I want the below code to check the created date of a customer, if they have been a customer for 6 months the price goes up as it was a promotion. I tried the below with no joy, I think as its just using the month and not taking the year into account. For example if a customer came onboard in September the 6 month would be the next year and it never change.
Thanks
$created_date = date('m',strtotime($customer_order['created_at']));
$current = date("m");
$curmonth = date("m");
$ordermonth = date("m",strtotime($udata['created_date']));
$m_dff = $curmonth - $ordermonth;
//print_r($m_dff."<br>");
if($m_dff > 6){
$unitcost = 19.99;
}
else{
$unitcost = 14.99;
}
strtotime() can be used more effectively than in your example, the following should do the trick
if(time() > strtotime($customer_order['created_at'] . ' +6 months')) {
$unitcost = 19.99;
} else {
$unitcost = 14.99;
}
$currentorder = date ('Y-m-d');
$createdaccount = date('Y-m-d', strtotime("+6 months",
strtotime($customer_order['created_at'])));
if($currentorder>=$createdaccount)
{
$unitcost = 19.99;
}
else
{
$unitcost = 14.99;
}
See if this works using DateTime objects to compare.
//set a general time zone at top of script
date_default_timezone_set('Europe/Amsterdam');
// if created_at is a valid dateTime string
$created = new \DateTime($customer_order['created_at']);
$current = new \DateTime();
$sixMonth = $created->add(new \DateInterval(‘P6M’));
if ($created < $current) {
// if created + 6 months is older than current
$price = 19.99;
} else {
$price = 14.99;
}
For more info see: https://secure.php.net/manual/en/book.datetime.php

Laravel Carbon get next occurrence of particular date from current date

Using Carbon with laravel 5.6.
I want write a code that give me next occurrence of date from current date.
E.g Give next 31st May date
Scenario 1 :
Input : $currentDate = '01-30-2019'; // MM-DD-YYYY format
Expected Output: $next31May = '05-31-2019';
Scenario 2 :
Input : $currentDate = '07-04-2019'; // MM-DD-YYYY format
Expected Output: $next31May = '05-31-2020';
Update:
I tried below code but not satisfy
<?php
public function nextOccurance()
{
$now = Carbon::now();
$month= $now->month;
$year = $now->year;
if($month > 6)
{
echo Carbon::createMidnightDate($year+1, 5, 31);
}
else
{
echo Carbon::createMidnightDate(null, 5, 31);
}
exit();
}
?>
Thank You in advance.
public function nextOccurance()
{
// the 31th of May of the current year
$day = Carbon::createFromFormat('m-d', '05-31');
$now = Carbon::now();
// If today after $day
if($now >= $day) {
// Gat a next year
$day->modify('next year');
}
echo $day->format('Y-m-d');
exit();
}
this is like to get the next birthday.
class Test
{
public static function getNextBirthday($date)
{
// set birthday from current year
$date = Carbon::createFromFormat('m-d-Y', $date);
$date->year(Carbon::now()->year);
// diff from 31 may to now
// its negative than add one year, otherwise use the current
if (Carbon::now()->diffInDays($date, false) >= 0) {
return $date->format('m-d-Y');
}
return $date->addYear()->format('m-d-Y');
}
}
echo Test::getNextBirtday('05-31-1990');
I wish this will help you to fix informed issue.
$event = Carbon::parse('31 May');
if (Carbon::now() >= $event){
$nextEvent = $event->addYear();
} else {
$nextEvent = $event;
}
echo $nextEvent->format('m-d-Y');
Carbon provides a nice and a fluent interface to this kind of stuff.
You can lastOfMonth() to get the last day of month. for adding year you can add addYear(1)
$now = Carbon::now();
$month= $now->month;
$year = $now->year;
if($month > 6)
{
echo $now->addMonth(5)->lastOfMonth();
}
else
{
echo $now->addYear(1);
}
exit();
}

php carbon check if now is between two times (10pm-8am)

$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
How can I check if the time of $now is within the timerange?
There are several ways to achieve that by using Carbon. One of the easiest ways is using createFromTimeString and between methods:
$now = Carbon::now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00')->addDay();
if ($now->between($start, $end)) {
// ¯\_(ツ)_/¯
}
Try this:
$time = Carbon::now();
$morning = Carbon::create($time->year, $time->month, $time->day, 8, 0, 0); //set time to 08:00
$evening = Carbon::create($time->year, $time->month, $time->day, 18, 0, 0); //set time to 18:00
if($time->between($morning, $evening, true)) {
//current time is between morning and evening
} else {
//current time is earlier than morning or later than evening
}
The true in $time->between($morning, $evening, true) checks whether the $time is between and including $morning and $evening. If you write false instead it checks just if it is between the two times but not including.
Actually, you could leave true away because it is set by default and not needed.
Check here for more information on how to compare dates and times with Carbon.
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$time = $now->format('H:i:s');
if ($time >= $start && $time <= $end) {
...
}
Should do it, but doesn't take date into consideration
You can reverse check algorithm.
<?php
$pushChannel = "general";
$now = Carbon::now();
$start = Carbon::createFromTime(8, 0);
$end = Carbon::createFromTime(22, 0);
if (!$now->between($start, $end)) {
$pushChannel = "silent";
$restrictStartTime = Carbon::createFromTime(22, 0, 0); //carbon inbuild function which will create todays date with the given time
$restrictEndTime = Carbon::createFromTime(8, 0, 0)->addDays(1); //this will create tomorrows date with the given time
$now = Carbon::now();
if($now->gt($restrictStartTime) && $now->lt($restrictEndTime)) {
.....
}
Please Try below code,
$start = '22:00:00';
$end = '08:00:00';
$now = Carbon::now('UTC');
$nowTime = $now->hour.':'.$now->minute.':'.$now->second;
if(strtotime($nowTime) > strtotime($start) && strtotime($nowTime) < strtotime($end) ) {
echo 'YES';
} else {
echo 'NO';
}
What Chris is trying to point out is if the endtime crosses over midnight then you must account for that.
This is not the cleanest way to do it but here is a method that seems to work.
private function isNowBetweenTimes($timezone, $startDateTime, $endDateTime) {
$curTimeLocal = Carbon::now($timezone);
$startTime = $curTimeLocal->copy();
$startTime->hour = $startDateTime->hour;
$startTime->minute = $startDateTime->minute;
$endTime = $curTimeLocal->copy();
$endTime->hour = $endDateTime->hour;
$endTime->minute = $endDateTime->minute;
if ($endTime->lessThan($startTime))
$endTime->addDay();
return ($curTimeLocal->isBetween($startTime, $endTime));
}
This example only cares about the hour and minutes and not the seconds but you can easily copy that as well. The key to this is comparing start and end time before comparing them to the current time and add a day to end time if end time is less than start time.
For complete solution which supports all start and end time range you can use bitwise XOR.
/*
* must using hours in 24 hours format e.g. set 0 for 12 pm, 6 for 6 am and 13 for 1 pm
*/
private $startTime = '0';
private $endTime = '6';
$currentHour = \Carbon\Carbon::now()->hour;
$start = $this->startTime > $this->endTime ? !($this->startTime <= $currentHour) : $this->startTime <= $currentHour;
$end = $currentHour < $this->endTime;
if (!($start ^ $end)) {
//Do stuff here if you want exactly between start and end time
}
an updated version of #AliN11's answer taking into account ranges accross two days or in the same day
$now = now();
$start = Carbon::createFromTimeString('22:00');
$end = Carbon::createFromTimeString('08:00');
if ($start > $end) {
$end = $end->addDay();
}
if ($now->between($start, $end)||$now->addDay()->between($start, $end)) {
//add statements
}
<?php
$now = date("H");
if ($now < "20") {
echo "Have a good day!";
}
Try this :
$start = 22; //Eg. start hour
$end = 08; //Eg. end hour
$now = Carbon::now('UTC');
if( $start < $now->hour && $now->hour < $end){
// Do something
}
#AliN11's (currently top) answer is good, but doesn't work as one would immediately expect, after midnight it just breaks, as raised in the comments by #Sasha
The solution is to reverse the logic, and check if the time is not between the inverse hours.
Here is an alternative that works as one would expect:
$now = Carbon::now();
$start = Carbon::createFromTimeString('08:00');
$end = Carbon::createFromTimeString('22:00');
if (! $now->between($start, $end)) {
// We're all good
}
Yes, the midnight plays a vital role in time duration. We can find now() being the given time range as follows:
$now = Carbon::now();
$start = Carbon::createFromTime('22', '00');
$end = Carbon::createFromTime('08', '00');
if ($start->gt($end)) {
if ($now->gte($start)) {
$end->addDay();
} elseif ($now->lte($end)) {
$start->subDay();
} else {
return false;
}
}
return $now->between($start, $end);

how can i calculate date not less than 18

I am trying to find the date not less than 18 years, I tried this following code, but its not working for me.
// validate birthday
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
echo "<br>";
echo 'test1-';
var_dump( $then );
exit;
//The age to be over, over +18
$min = strtotime('+18 years', $then);
if(time() < $min) {
die('Not 18');
}
}
$res = validateAge('2016-02-29', $min = 18);
var_dump($res);
I fyou see the above question, you can see that, date is not valid, even if i pass the wrong date, its shows the $then = strtotime($then);
var_dump($then) show the int
my question is, how its printing the timestamp, event if we passing the invalid date.
Your logic is correct. Remove die, exit and echo which is not needed
function validateAge($then, $min)
{
// $then will first be a string-date
$then = strtotime($then);
//The age to be more then min years
$min = strtotime('+'. $min . ' years', $then);
return time() > $min;
}
$res = validateAge('2016-02-29', $min = 18);
echo $res ? 'O\'key' : "Not $min years";
demo
Try maybe something like this
function compareAge($date,$min=18)
{
$strdate = strtotime($date);
$curdate = strtotime("today");
$datefin=date("Ymd",$curdate)-date("Ymd",$strdate);
$age=substr($datefin,0,strlen($datefin)-4);
return $age>=$min;
}
var_dump(compareAge("2013-05-13"));
DEMO
you could use this method:
public function validateAge($then)
{
$then= date_create($then);
$now = date_create("now");
$diff = $now->diff($then);
if ($diff->y > 18)
{
die('not 18');
}
}
Duplicate:
Calculating number of years between 2 dates in PHP
use the datetime object to save all sorts of pain. Its so much more simple.
function validateAge(DateTime $then, $min = 18)
{
$now = new DateTime();
$minimum = clone($now); // you could just modify now, but this is simpler to explain
$minimum->modify("-$min years");
if($then < $minimum) {
return false;
}
return true;
}
echo validateAge(new DateTime('1-1-1997')) ? 'true' : 'false'; // returns false
echo validateAge(new DateTime('1-1-1999')) ? 'true' : 'false'; // returns true
see example
Wow, so many try-hards.
In case you like is simple:
<?php
function validateAge($date) {
return date_create('18 years ago') > date_create($date);
}
var_dump(
validateAge('2010-10-05'),
validateAge('1992-09-02')
);
OUTPUT
bool(false)
bool(true)
Play with me on 3v4l.org
Edit: Also works with the $min parameter:
<?php
function validateAge($date, $min) {
return date_create("$min years ago") > date_create($date);
}
var_dump(
validateAge('2010-10-05', 18),
validateAge('1992-09-02', 18)
);

check upcomming birthday in a week 2 week or in a month using php

how to check is birthday is in this week,2week,or in month i have used below code to check but it return wrong calculation.
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d,$y);
}
$countdown = round(($myevent - $today)/86400);
if ($countdown <= $days)
{
return true;
}
return false;
}
Try this:
function CountDown($birthdate, $days=7)
{
# create today DateTime object
$td = new DateTime('today');
# create birth DateTime object, from format Y/d/m
$bd = DateTime::createFromFormat('!Y/d/m', $birthdate);
# set current year to birthdate
$bd->setDate($td->format('Y'), $bd->format('m'), $bd->format('d'));
# if birthdate is still in the past, set it to new year
if ($td > $bd) $bd->modify('+1 year');
# calculate difference in days
$countdown = $bd->diff($td)->days;
# return true if day difference is within your range
return $countdown <= $days;
}
demo
This worked for me
class Birthday{
public function CountDown($birthdate, $days=7)
{
list($y,$d,$m) = explode('/',$birthdate);
$today = time();
$event = mktime(0,0,0,$m,$d,$y);
$apart = $event - $today;
if ($apart >= -86400)
{
$myevent = $event;
}
else
{
$myevent = mktime(09,0,0,$m,$d);
}
$countdown = round(($myevent - $today)/86400);
if (($countdown <= $days))
{
return true;
}
return false;
}
}
$bday = new Birthday;
$count = $bday->CountDown("1969/16/11"); //today is 2014/14/11
var_dump($count); //returns true.
I just removed the year from the mktime() in $myevent. This changed the answers to be accurate.
The other way that it was being done made $countdown to be a huge negative number.

Categories