Click here to Skip to main content
Licence Public Domain
First Posted 13 Sep 2008
Views 42,304
Downloads 706
Bookmarked 33 times

C# Class for Calculating Sunrise and Sunset Times

By | 13 Sep 2008 | Article
A class for calculating sunrise and sunset times, implemented as a thread-safe Singleton

Introduction

This simple C# Singleton class calculates the sunrise and sunset times for a given date.

Background

After searching for a simple and decent implementation for calculating sunrise and sunset times for given dates, and trying several implementations that were either too complicated to migrate to C# or simply not working, I found a simple yet working JavaScript implementation here.

I migrated the code to C#, tweaking it a little so that it provides accurate calculations. Also, I wrapped it as a Singleton class (assuming multiple instances would not be required for such a class) and added a lock to the main calculation method, in order to make it thread safe (via blocking).

Using the Code

The singleton class SunTimes can be called from anywhere in your code by calling SunTimes.Instance.

The class contains a single method, with one overload, named CalculateSunRiseSetTimes(). You simply call this method, provide it with three input parameters: latitude and longitude of the desired location, and date for which to calculate. Moreover, you need to pass it four (4) output (ref) parameters: riseTime (sunrise time), setTime (sunset time), isSunrise (does the sun rise that day at all?) and isSunset (does the sun set that day at all?).

The method returns a boolean value if the calculation succeeds (it will fail, if the time zone and longitude are incompatible).

Here is a sample usage of the class:

...

DateTime date = DateTime.Today;
bool isSunrise = false;
bool isSunset = false;
DateTime sunrise = DateTime.Now;
DateTime sunset = DateTime.Now;

// Print out the Sunrise and Sunset times for the next 20 days
for (int i=0; i<20; i++)
{
                                                // Coordinates of Tel-Aviv
     SunTimes.Instance.CalculateSunRiseSetTimes(new SunTimes.LatitudeCoords
                                   (32, 4, 0, SunTimes.LatitudeCoords.Direction.North),
                                                new SunTimes.LongitudeCoords
                                   (34, 46, 0, SunTimes.LongitudeCoords.Direction.East),
                                                date, ref sunrise, ref sunset, 
			                     ref isSunrise, ref isSunset);

     Debug.Print(date + '': Sunrise @'' + sunrise.ToString('HH:mm') + ''  
				Sunset @'' + sunset.ToString(''HH:mm''));

     date = date.AddDays(1); // Move to the next day
}

...

Points of Interest

This implementation is not in particular fancy, not is it the slickest design, but hey - it does the work (at least as far as I've tested it). I will be happy to get any comments (not on its design, please, only if you detect any actual bugs).

History

  • 14-Sep-2008: Uploaded the class implementation

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication

About the Author

Zacky Pickholz

CEO
Homee
Israel Israel

Member

With 15 years of experience in the IT/High-Tech industry, as developer, team-leader and product manager.
 
Fields of expertise include: Networks, Security, Gaming, Embedded/Real Time and Web applications.
 
I have written many applications, both in structural languages (C, Pascal, Fortran, VB) and OO languages (C++, C#, J2SE/J2EE) as well as in scripting/interpreted/web languages (HTML, JavaScript, LUA Script, PHP, VBScript).
 
Today, Co-Founder and CEO of Robo Smart Solutions (www.robo.co.il).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionisSunset and isSunrise PinmemberDNZ_at22:50 28 Dec '11  
GeneralEast/West Bug Pinmembersorgal0:49 3 Mar '11  
QuestionWhat about elevation and twilight? PinmemberMark Kestenbaum2:19 24 Feb '10  
GeneralKILLER BUG [modified] PinmemberJools55713:09 26 Apr '09  
GeneralRe: KILLER BUG PinmemberZacky Pickholz22:54 5 May '09  
GeneralNice but one question [modified] PinmemberRafone19:50 16 Mar '09  
GeneralRe: Nice but one question PinmemberZacky Pickholz22:51 21 Apr '09  
Hey Rafone,
 
Thanks for the input, I now know the code might not work worldwide and potentially needs some fixing.
 
I don't think the (just) an issue of DST. Essentially the code should give the exact sunrise and sunset times down to the minute level, and there is a discrepancy of 6 minutes between the calculated time and your local weather pages (which I assume are accurate).
 
DST might cause the 1 hour diff, but I'm more alarmed with the 6 minutes diff.
 
I wish I could give you a better solution, but unfortunately I know zilch about astronomy as opposed to my coding knowledge. I merely adapter/adjusted the code from JavaScript.
 
Perhaps some other user could provide us with a resolution?
GeneralRe: Nice but one question PinmemberPIEBALDconsult4:13 22 Apr '09  
GeneralRe: Nice but one question PinmemberRafone7:05 22 Apr '09  
GeneralRe: Nice but one question PinmemberZacky Pickholz22:49 5 May '09  
GeneralRe: Nice but one question PinmemberRafone2:46 6 May '09  
GeneralRe: Nice but one question PinmemberZacky Pickholz10:29 6 May '09  
GeneralRe: Nice but one question PinmemberRafone11:26 6 May '09  
QuestionWhy not static? PinmemberPIEBALDconsult17:08 9 Jan '09  
AnswerRe: Why not static? PinmemberZacky Pickholz22:41 21 Apr '09  
GeneralRe: Why not static? PinmemberPIEBALDconsult4:02 22 Apr '09  
QuestionHow do I reference this in VB.Net? Pinmemberpmannino23:52 8 Jan '09  
AnswerRe: How do I reference this in VB.Net? PinmemberZacky Pickholz22:43 21 Apr '09  
GeneralProblem getting sunrise and sunset to output. Pinmembernewb2vb5:05 4 Nov '08  
GeneralRe: Problem getting sunrise and sunset to output. PinmemberMedlan5:52 4 Nov '08  
Generalerror Pinmemberharrifer8:19 31 Oct '08  
GeneralRe: error Pinmemberrsam_london15:19 31 Oct '08  
GeneralProblem with rounding the UtcOffset Pinmemberrsam_london17:11 29 Oct '08  
GeneralRe: Problem with rounding the UtcOffset PinmemberRedFraggle0:46 4 Feb '12  
QuestionTwilight times? Pinmemberacasia213:07 9 Oct '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120604.1 | Last Updated 13 Sep 2008
Article Copyright 2008 by Zacky Pickholz
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid