Finding daylight times in PHP

PHP has a huge number of functions and amazingly these include calculation of sunset and sunrise times, so its easy to calculate if its currently daylight using PHP.

I’ve created the is_daylight.php script to check if its currently in daylight hrs for a given latitude and longitude.

I’m using this to take webcam photos only in daylight hrs, and I allow 30 minutes leeway either side of sunset or sunrise when a photo will still usually come out ok.

<?php
 
        /**
         * @file is_daylight.php
         * Exits with 1 if currently its daylight at Pasture Houses
         **/
 
function timeIsEarlierThan($timestamp, $time_string, $adjust_by_seconds = 0) {
        $timestamp_hours = date('H', $timestamp);
        $timestamp_minutes = date('i', $timestamp);
        $time1_in_seconds = $timestamp_hours * 60 * 60 + $timestamp_minutes * 60;
        $midnight_time = strtotime("00:00");
        $time2_in_seconds = strtotime($time_string) - $midnight_time;
        $time2_in_seconds += $adjust_by_seconds;
        return $time1_in_seconds < $time2_in_seconds;
}
 
        $now = time();
        $latitude = 0;          // set your latitude and longitude here
        $longitude = 0;
        $sunset_time = date_sunset($now, SUNFUNCS_RET_STRING, $latitude, $longitude);
        $sunrise_time = date_sunrise($now, SUNFUNCS_RET_STRING, $latitude, $longitude);
 
        // Its night time if earlier than the sunrise or later than sunset
        // 30 mins either side is allowed
        if (timeIsEarlierThan($now, $sunrise_time, -30*60) || !timeIsEarlierThan($now, $sunset_time, 30*60)) {
                //echo "Its night time". PHP_EOL;
                exit(0);
        } else
                exit(1);

On the Raspberry Pi I use this so I can have a simple cron job to take an hourly photo when its daylight.

#!/bin/bash

output=`php -f /home/pi/python/is_daylight.php`
is_daylight=$?

if [ "$is_daylight" -eq "1" ]; then
DATE=$(date +"%Y-%m-%d_%H%M")
FILENAME="/home/pi/webcam_photos/$DATE.jpg"
echo "Taking photo $FILENAME."
raspistill -vf -hf -o $FILENAME
fi

Posted on August 9, 2020 at 7:04 pm

No Comments