Skip to content

Instantly share code, notes, and snippets.

@nanoDBA
Last active January 2, 2025 17:53
Show Gist options
  • Select an option

  • Save nanoDBA/2b50ba01ad5736c4eb89040f3a2b42bc to your computer and use it in GitHub Desktop.

Select an option

Save nanoDBA/2b50ba01ad5736c4eb89040f3a2b42bc to your computer and use it in GitHub Desktop.
How many minutes of daylight are there in a given day?
# 🌞 Looking forward to more daylight! 🌞
# https://stackoverflow.com/questions/63236774/powershell-return-only-sunrise-sunset-time/63237047#63237047
# using API from https://sunrise-sunset.org/api
# Location Coordinates (enter your location)
$lat = 35.787743 # Latitude
$long = -78.644257 # Longitude
# Fetching Data
Write-Host "β˜€οΈ Fetching daylight data... Every day gets a little brighter! β˜€οΈ`n"
# Header
Write-Host ("{0,-12} {1,-10} {2,-10} {3,-12} {4,-15}" -f "πŸ“… Date", "πŸŒ… Sunrise", "πŸŒ‡ Sunset", "⏳ Daylight", "πŸ“ˆ Gain (mins)") -ForegroundColor Cyan
Write-Host ("{0,-12} {1,-10} {2,-10} {3,-12} {4,-15}" -f "----------", "----------", "----------", "-----------", "---------------") -ForegroundColor Cyan
Write-Host "───────────────────────────────────────────────────────────────"
# Variables
$initialDaylight = $null
$totalGain = 0
# πŸ“… Date Range Explanation:
# The range operator (-5..1) generates a sequence of integers from -5 to 1.
# Each integer represents a day offset from the current date:
# - -5 means 5 days ago
# - -4 means 4 days ago
# - ...
# - 0 means today
# - 1 means tomorrow
# This allows us to fetch data for multiple days in one loop.
-5..1 | ForEach-Object {
$Date = (Get-Date).AddDays($_) | Get-Date -Format "yyyy-MM-dd"
$Daylight = (Invoke-RestMethod "https://api.sunrise-sunset.org/json?lat=$lat&lng=$long&formatted=0&date=$Date").results
$Sunrise = ($Daylight.Sunrise | Get-Date -Format "HH:mm")
$Sunset = ($Daylight.Sunset | Get-Date -Format "HH:mm")
$DayLength = [math]::round($Daylight.day_length / 3600, 2) # In hours
$DayLengthMins = [math]::round($Daylight.day_length / 60, 1) # In minutes
# Calculate cumulative gain
if ($initialDaylight -eq $null) {
$initialDaylight = $DayLengthMins
$GainText = "🟒 Start"
} else {
$totalGain = [math]::round($DayLengthMins - $initialDaylight, 1)
$GainText = if ($totalGain -ge 0) { "+$totalGain" } else { "$totalGain" }
}
# Print Row
Write-Host ("{0,-12} {1,-10} {2,-10} {3,-12} {4,-15}" -f $Date, $Sunrise, $Sunset, $DayLength, $GainText) -ForegroundColor Yellow
}
# Footer Message
Write-Host "───────────────────────────────────────────────────────────────"
Write-Host "`nπŸ’‘ Every extra moment of daylight brings us closer to brighter days. Keep those curtains open and let the light in! β˜€οΈ" -ForegroundColor Green
@nanoDBA
Copy link
Author

nanoDBA commented Jan 2, 2025

Worked with AI using the initial version to iterate and appear more visually appealing 🌞

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment