Skip to content

Instantly share code, notes, and snippets.

@lunule
Last active April 26, 2020 16:00
Show Gist options
  • Save lunule/0aee1dbc595902283b817611af1f5587 to your computer and use it in GitHub Desktop.
Save lunule/0aee1dbc595902283b817611af1f5587 to your computer and use it in GitHub Desktop.
[Different Shit by Daytime vs Nighttime] Displaying different shit if user's CLIENT's (not OS's which is unaltered even if she's using VPN!!!) current time says it's daytime/nighttime #daytime #nighttime #day #night #daylight #goldenhour #darkness #dark #light #geo #geoip #location #latitude #longitude
<?php
/**
* APIs and jQuery plugins used:
*
* Geo IP Lookup - to get longitude, latitude and time zone data by ip
* https://json.geoiplookup.io/
*
* Suncalc - Calculate Sun/Moon positions and phases
* https://github.com/mourner/suncalc
*
* World Time API - to get the CLIENT's current time data instead of the user's OS' current time!!!
* http://worldtimeapi.org/
*
* FUTOTTAK MÉG:
* https://ipinfodb.com/
* (pro: FREE, no request limit, returns everything!!!, con: accuracy is lower compared to a similar service with paid plans)
* https://ip-api.com/
* (pro: FREE, con: doesn't return time zone or other time related date, location only)
* https://ipgeolocation.io/pricing.html
* (pro: FREE below 1000 requests per day (30.000 requests per month), con: none, it returns
* everything: location info, timezone, current time, ip, you name it)
*
*/
?>
<script src="/suncalc.js"></script>
<script>
$(document).ready(function() {
/** Get user's location if HTML Geolocation API is available
*
* @see https://geoiplookup.io
* FYKI - FREE ONLY for non-commercial use, and below 10.000 requests/hour
*/
const fetchUrl = 'https://json.geoiplookup.io/';
let lat = false,
long = false,
timeZone = false,
ip = false;
$.getJSON(fetchUrl).done(function(location) {
lat = location.latitude,
long = location.longitude,
timeZone = location.timezone_name,
ip = location.ip;
/**
* Let's see if user's location has nighttime (darkness) or daytime (daylight)
* We use Suncalc to get the golden hour end time.
*
* @see https://github.com/mourner/suncalc
*
* Then we compare the golden hour end time with the current time -
*/
if ( lat && long ) {
const times = SunCalc.getTimes(new Date(), lat, long),
// format golden hour (before sunset) and golden hour end (after
// sunrise) times from the Date object
goldenHour = Date.parse( times.goldenHour ),
goldenHourEnd = Date.parse( times.goldenHourEnd );
$.getJSON('http://worldtimeapi.org/api/timezone/' + timeZone).done(function(data) {
const clientTime = Date.parse( data.datetime );
if ( goldenHourEnd <= clientTime && clientTime <= goldenHour )
$('body').addClass('daylight');
})
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment