Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to check the season of the year and set a class accordingly

Tags:

php

I have a website which uses 4 different background images for the header area which visually corresponds to the season of the ear (summer, autumn etc.) – for the summer timeframe I use one image, for the autumn – another one and so on. The problem is that I have to manually change those images once the season of the year changes.

Maybe someone could show how would it be possible to check the current time / season of the year and then print the corresponding classes to the header element (.summer, .autumn etc.)?

I assume using PHP would be the way.

like image 823
Daniel Avatar asked Nov 30 '16 16:11

Daniel


Video Answer


2 Answers

As I stated in the comments, this is an interesting challenge because the dates of seasons are always changing and different depending what part of the world you live in. Your server time and the website visitor's local time are also a factor.

Since you've stated you're just interested in a simple example based on server time and you're not concerned with it being exact, this should get you rolling:

// get today's date
$today = new DateTime();
echo 'Today is: ' . $today->format('m-d-Y') . '<br />';

// get the season dates
$spring = new DateTime('March 20');
$summer = new DateTime('June 20');
$fall = new DateTime('September 22');
$winter = new DateTime('December 21');

switch(true) {
    case $today >= $spring && $today < $summer:
        echo 'It\'s Spring!';
        break;

    case $today >= $summer && $today < $fall:
        echo 'It\'s Summer!';
        break;

    case $today >= $fall && $today < $winter:
        echo 'It\'s Fall!';
        break;

    default:
        echo 'It must be Winter!';
}

This will output:

Today is: 11-30-2016
It's Fall!
like image 160
mister martin Avatar answered Oct 13 '22 00:10

mister martin


One might consider this necromancy, Yet when I was looking for ready to use method that does this I've got here. Mister Martin answer was good assuming the year will not changes, here is my snippet, might be useful for someone in future:

private function timestampToSeason(\DateTime $dateTime): string{
    $dayOfTheYear = $dateTime->format('z');
    if($dayOfTheYear < 80 || $dayOfTheYear > 356){
        return 'Winter';
    }
    if($dayOfTheYear < 173){
        return 'Spring';
    }
    if($dayOfTheYear < 266){
        return 'Summer';
    }
    return 'Fall';
}

cheers!

like image 44
MjhaL Avatar answered Oct 12 '22 23:10

MjhaL