Laravel Carbon get next occurrence of particular date from current date - php

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

Related

Get remaining dates from Array

I have one leave array,(retrive from table)
$leavearray=array("2019-10-22","2019-10-23","2019-10-25","2019-10-26","2019-10-28","2019-10-30");
If I give 2,it should return next 2nd working day-2019-10-27
If I give 1,it should return next 1st working day-2019-10-24
Can you help me to get this.
$priority=2;
$date="2019-10-22";
echo $this->checknextdate($date,$priority);
function checknextdate($date,$priority){
$leavearray=array("2019-10-22","2019-10-23","2019-10-25","2019-10-26","2019-10-28","2019-10-30");
do{
if(in_array($date,$leavearray))
{
$date = date('Y-m-d', strtotime($date.'+1 day'));
}else{
return $date;
$checkok=1;
exit();
}
} while ($checkok==1);
}
I think you can do it like this, using your original code, although this might not be the perfect solution:
$priority = 2;
$date = "2019-10-22";
echo checknextdate($date,$priority);
function checknextdate($date, $priority){
$leavearray = array("2019-10-22","2019-10-23","2019-10-25","2019-10-26","2019-10-28","2019-10-30");
do{
$date = date('Y-m-d', strtotime($date . '+1 day'));
if (!in_array($date, $leavearray)) {
$priority--;
}
} while ($priority > 0);
return $date;
}

Check Date if Saturday or Sunday [duplicate]

This function seems to only return false. Are any of you getting the same? I'm sure I'm overlooking something, however, fresh eyes and all that ...
function isweekend($date){
$date = strtotime($date);
$date = date("l", $date);
$date = strtolower($date);
echo $date;
if($date == "saturday" || $date == "sunday") {
return "true";
} else {
return "false";
}
}
I call the function using the following:
$isthisaweekend = isweekend('2011-01-01');
If you have PHP >= 5.1:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
otherwise:
function isWeekend($date) {
$weekDay = date('w', strtotime($date));
return ($weekDay == 0 || $weekDay == 6);
}
Another way is to use the DateTime class, this way you can also specify the timezone.
Note: PHP 5.3 or higher.
// For the current date
function isTodayWeekend() {
$currentDate = new DateTime("now", new DateTimeZone("Europe/Amsterdam"));
return $currentDate->format('N') >= 6;
}
If you need to be able to check a certain date string, you can use DateTime::createFromFormat
function isWeekend($date) {
$inputDate = DateTime::createFromFormat("d-m-Y", $date, new DateTimeZone("Europe/Amsterdam"));
return $inputDate->format('N') >= 6;
}
The beauty of this way is that you can specify the timezone without changing the timezone globally in PHP, which might cause side-effects in other scripts (for ex. Wordpress).
If you're using PHP 5.5 or PHP 7 above, you may want to use:
function isTodayWeekend() {
return in_array(date("l"), ["Saturday", "Sunday"]);
}
and it will return "true" if today is weekend and "false" if not.
Here:
function isweekend($year, $month, $day)
{
$time = mktime(0, 0, 0, $month, $day, $year);
$weekday = date('w', $time);
return ($weekday == 0 || $weekday == 6);
}
The working version of your code (from the errors pointed out by BoltClock):
<?php
$date = '2011-01-01';
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
echo "true";
} else {
echo "false";
}
?>
The stray "{" is difficult to see, especially without a decent PHP editor (in my case). So I post the corrected version here.
For guys like me, who aren't minimalistic, there is a PECL extension called "intl".
I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".
Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.
EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).
This works for me and is reusable.
function isThisDayAWeekend($date) {
$timestamp = strtotime($date);
$weekday= date("l", $timestamp );
if ($weekday =="Saturday" OR $weekday =="Sunday") { return true; }
else {return false; }
}
As opposed to testing the explicit day of the week string or number, you can also test using the relative date this weekday of the supplied date.
A direct comparison between the values is not possible without a workaround, as the use of weekday resets the time of the supplied date to 00:00:00.0000.
DateTimeInterface objects
$date->setTime(0, 0, 0) != $date->modify('this weekday');
DateTimeInterface Method
A simple method to implement to ensure the supplied date object is not changed.
function isWeekend(DateTimeInterface $date): bool
{
if ($date instanceof DateTime) {
$date = DateTimeImmutable::createFromMutable($date);
}
return $date->setTime(0,0,0) != $date->modify('this weekday');
}
isWeekend(new DateTimeImmutable('Sunday')); //true
strtotime method
With strtotime you can compare with the date('Yz') format. If the Yz value changes between the supplied date and this weekday, the supplied date is not a weekday.
function isWeekend(string $date): bool
{
return date('Yz', strtotime($dateValue)) != date('Yz', strtotime($dateValue . ' this weekday'));
}
isWeekend('Sunday'); //true
Example
https://3v4l.org/TSAVi
$sunday = new DateTimeImmutable('Sunday');
foreach (new DatePeriod($sunday, new DateInterval('P1D'), 6) as $date) {
echo $date->format('D') . ' is' . (isWeekend($date) ? '' : ' not') . ' a weekend';
}
Result
Sun is a weekend
Mon is not a weekend
Tue is not a weekend
Wed is not a weekend
Thu is not a weekend
Fri is not a weekend
Sat is a weekend

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

Current time plus one for date validation?

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')) {

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