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
Related
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();
}
function validateDate($date, $format = 'm-Y') {
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
validateDate('09-2017', 'm-Y');
function was copied from this answer or php.net
I'm very puzzled to why this returns false while it returns true for the previous months. Any ideas?
It's because you're not supplying a day, so it's using the current day by default. Current day is 31, but September only has 30 days, so it skips to October 1st.
Look at this example:
function validateDate($date, $format = 'm-Y') {
$d = DateTime::createFromFormat($format, $date);
echo $d->format("d-".$format); // added the day for debugging
return $d && $d->format($format) == $date;
}
var_dump(validateDate('08-2017', 'm-Y')); // 31-08-2017, true
var_dump(validateDate('09-2017', 'm-Y')); // 01-10-2017, there's no 31-09-2017, false
function was copied from this answer or php.net
This is a little rudimentary, but you can detect if there's no d in the format and manually set it to 1 to avoid this:
<?php
function validateDate($date, $format = 'm-Y') {
if (strpos($format, "d") === false) {
$format = "d ".$format;
$date = "01 ".$date;
}
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) === $date;
}
var_dump(validateDate('08-2017', 'm-Y')); // 31-08-2017, true
var_dump(validateDate('09-2017', 'm-Y')); // 01-09-2017, true
If you are not supplying a day. current one is used; just like explained in previous answer.
But this can be quickly solved with one format sign: !, which resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to the Unix Epoch; see format table.
Fix:
function validateDate($date, $format = 'm-Y') {
$d = DateTime::createFromFormat('!'.$format, $date);
return $d && $d->format($format) == $date;
}
function was copied from this answer or php.net
I have 2 dates like this YYYY-mm-dd and I would like to check if these 2 dates are a weekend.
I have this code but it only tests 1 date and I don't know how to adapt it; I need to add a $date_end.
$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";
}
A couple of hints:
date('N') gives you normalised week day you can test against (no need to use localised strings)
Wrap it all in a custom function and you're done
You can use shorter code to check for weekend => date('N', strtotime($date)) >= 6.
So, to check for 2 dates — and not just 1 — use a function to keep your code simple and clean:
$date1 = '2011-01-01' ;
$date2 = '2017-05-26';
if ( check_if_weekend($date1) && check_if_weekend($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend($date1) || check_if_weekend($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend($date) {
return (date('N', strtotime($date)) >= 6);
}
Using your existing code, which is slightly longer, following is how you would check for 2 dates:
$date1 = '2011-01-01' ;
$date2 = '2017-05-27';
if ( check_if_weekend_long($date1) && check_if_weekend_long($date2) ) {
echo 'yes. both are weekends' ;
} else if ( check_if_weekend_long($date1) || check_if_weekend_long($date2) ) {
echo 'no. only one date is a weekend.' ;
} else {
echo 'no. neither are weekends.' ;
}
function check_if_weekend_long($date_str) {
$timestamp = strtotime($date_str);
$weekday= date("l", $timestamp );
$normalized_weekday = strtolower($weekday);
//echo $normalized_weekday ;
if (($normalized_weekday == "saturday") || ($normalized_weekday == "sunday")) {
return true;
} else {
return false;
}
}
Merging multiple answers into one and giving a bit extra, you'd come to the following:
function isWeekend($date) {
return (new DateTime($date))->format("N") > 5 ? true : false;
}
Or the long way:
function isWeekend($date) {
if ((new DateTime($date))->format("N") > 5) {
return true;
}
return false;
}
You can use the strtotime(); and date() functions to get the day of the date, and then check if is sat o sun
function check_if_weekend($date){
$timestamp = strtotime($date);
$day = date('D', $timestamp);
if(in_array($day, array('sun', 'sat'))
return true;
else return false;
}
I'm running a date validation in PHP:
public function isValidDate($date) {
$valid = false;
$valid_formats = array(
'Y-m-d',
'm-d-Y',
'Y/m/d',
'm/d/Y'
);
foreach ($valid_formats as $format) {
if (!$valid) {
$d = \DateTime::createFromFormat($format, $date);
$valid = $d && $d->format($format) == $date;
}
}
return $valid;
}
What's odd is that if the format is m/d/Y, and I pass 1/1/2016 to it, it is false, because when I run $d->format(m/d/Y), I get a result of 01/01/2016.
Any ideas on why it is enforcing the leading zeros?
Thats because you have not defined a valid format that matches a date with only one character day and month fields
function isValidDate($date) {
$valid = false;
$valid_formats = array(
'Y-m-d',
'm-d-Y',
'Y/m/d',
'm/d/Y',
'j/n/Y', // <- NEW day/month 1/1
'n/j/Y' // <- NEW month/day 1/1
);
foreach ($valid_formats as $format) {
if (!$valid) {
$d = \DateTime::createFromFormat($format, $date);
$valid = $d && $d->format($format) == $date;
}
}
return $valid;
}
echo isValidDate('1/1/2016') ? 'VALID' : 'INVALID';
There may be others you need to add as well!
I found the answer, from W3Schools.
It seems the official documentation is missing some format options:
d - Day of the month; with leading zeros
j - Day of the month; without leading zeros
m - Month (01-12)
n - Month (1-12)
'j' and 'n' are missing from http://php.net/manual/en/dateinterval.format.php
I'm looking for a function that calculates years from a date in format: 0000-00-00.
Found this function, but it wont work.
// Calculate the age from a given birth date
// Example: GetAge("1986-06-18");
function getAge($Birthdate)
{
// Explode the date into meaningful variables
list($BirthYear,$BirthMonth,$BirthDay) = explode("-", $Birthdate);
// Find the differences
$YearDiff = date("Y") - $BirthYear;
$MonthDiff = date("m") - $BirthMonth;
$DayDiff = date("d") - $BirthDay;
// If the birthday has not occured this year
if ($DayDiff < 0 || $MonthDiff < 0)
$YearDiff--;
}
echo getAge('1990-04-04');
outputs nothing :/
i have error reporting on but i dont get any errors
Your code doesn't work because the function is not returning anything to print.
As far as algorithms go, how about this:
function getAge($then) {
$then_ts = strtotime($then);
$then_year = date('Y', $then_ts);
$age = date('Y') - $then_year;
if(strtotime('+' . $age . ' years', $then_ts) > time()) $age--;
return $age;
}
print getAge('1990-04-04'); // 19
print getAge('1990-08-04'); // 18, birthday hasn't happened yet
This is the same algorithm (just in PHP) as the accepted answer in this question.
A shorter way of doing it:
function getAge($then) {
$then = date('Ymd', strtotime($then));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
}
An alternative way to do this is with PHP's DateTime class which is new as of PHP 5.2:
$birthdate = new DateTime("1986-06-18");
$today = new DateTime();
$interval = $today->diff($birthdate);
echo $interval->format('%y years');
See it in action
A single line function can work here
function calculateAge($dob) {
return floor((time() - strtotime($dob)) / 31556926);
}
To calculate Age
$age = calculateAge('1990-07-10');
You need to return $yearDiff, I think.