Click here to Skip to main content
Click here to Skip to main content

Sunrise/Sunset Calculations

By , 14 Dec 2000
 
  • Download source files - 4 Kb
  • Download demo project - 12 Kb
  • Introduction

    I searched the web for a piece of code that calculates the Sunrise/Sunset based on the Date and a latitude and longitude, but could not find one in C++ that was freely available. People have FreeWare out there, but were unwilling to give out the source as they deemed it to "valuable". So I took it upon myself to convert one of the other freely available pieces of code, and convert it for everyone to use.

    I have written a the following C++ code. It is based heavily on the Javascript I obtained directly from the NOAA. I find that many applications may have a use for this information, so feel free to use it to make your own FreeWare tray applications, or any other Utility Programs.

    The Main three functions are:

    CTime GetSunset(double dLat,double dLon,CTime time);
    CTime GetSunrise(double dLat,double dLon,CTime time);
    CTime GetSolarNoon(double dLon, CTime time);
    

    which take in Latitude and Longitude values as doubles and a CTime with the Date that you want to calculate the SR/SS for. It returns a CTime in UTC.

    I have included a non-MFC Tray icon class I have written, with the example.. It has the basic functionality to display a tray icon, and can be used in MFC, Win32 and ATL applications. Probably not as good as the newest CSystemTray, but I use it with Win32 to make very small footprint applications!!

    I have also added more functionality to the demo, as the way I originally submitted it, it had very little actual functionality. I also added the code so it is converted from UTC as well.

    Hope someone finds it Useful....

    License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    Brian Heilman
    Software Developer Birdsoft
    United States United States
    Member
    Software Engineer with years of Visual C++ and Objective-C
    experience.
     
    Developed Windows Mobile applications including All-In Hold 'Em, Extreme Agenda, and The Dog Ate It.
     
    Now mostly iOS development with the popular title Extreme Agenda as a flagship.

    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.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    Bugyou have a bug in minus locationmemberMember 769785810 Sep '11 - 22:00 
    the program give error for minus location and anyway calculate the tims..... fix it
     
    jerusalem is in minus location (-35) Smile | :)
    QuestionGreat stuff is there a fix for DST?memberRobert Valentino6 Apr '11 - 3:45 
    Hello:
     
    Tried your demo and really cool stuff, thanks so much for posting this code.
     
    When I try the demo it says for my lat / lon (36.560643 / 77.826284) that the Sunrise is 5:51:14 am and the Sunset is 18:37:00 and according to this website ("http://www.calendar-updates.com/sun.asp?PostalCode=23887[^]") the Sunrise is 6:51 and Sunset is 19:38 - this is for April 6th 2011.
     
    There site does not report Solar Noon.
     
    I have to assume the times are off because I am in the East Coast (EST) and we are currently in Daylight Savings Time (DST) and this is not being taken into account?
     
    Before I dive into the code and try and fix something that has already been fixed I was just wondering if there was a different version around that handled DST (assuming that is the problem).
     
    Again great stuff.
     
    Thanks
     
    BobVal
    GeneralhelpmemberMember 76555218 Feb '11 - 5:10 
    I can not get this to run every time i try it says : fatal error C1083: Cannot open include file: 'afxwin.h': No such file or directory can anyone help with this?
    GeneralMy vote of 2membercraig.miller26 May '10 - 13:01 
    Errors in code, and basic calculations don't work. This article needs to be fixed or removed.
    GeneralRe: My vote of 2memberPat Kujawa24 Mar '11 - 5:46 
    Would you elaborate on some of the errors you encountered (or which calculations seem faulty)?
    QuestionCan i have C# version of this codemembertoashokin15 Sep '09 - 23:01 
    Please provide c# versoin of the code also.
    AnswerRe: Can i have C# version of this codememberPat Kujawa24 Mar '11 - 5:46 
    C# Class for Calculating Sunrise and Sunset Times[^]
    QuestionDoes anyone know how to get the Noon Rise / set times from this?memberpeterdrozd20 Aug '08 - 3:52 
    Hi;
    I want to get the sunrise/set times and moon rise/set times for a longitude and latitude.
     
    Does anyone know how to get the Noon Rise / set times from this?
     
    thanks
     
    -peter
    QuestionDid anyone do a clean up?memberJustASoftwareGuy6623 Dec '06 - 8:50 

    It looks like there were several problems with UTC, Daylight savings time, etc.
     
    Did anyone go through an clean up those problems or do they have to be patched one at a time?
     
    Thanks.
     

    Generalwrong result? helpmemberanqincmt5 Dec '05 - 13:50 
    count out with sun times(http://www.fv01.dial.pipex.com/world.htm?suntimes.shtml[^]
    guangzhou china N23E113:(2005-12-06)
    sunrise 06:54:29
    midday 12:17:58
    sunset 17:41:20
    daylength 10:46:52
    count out with your demo
    sunrise 2005-12-6 21:59:18
    sunset 2005-12-7
    solar noon 2005-12-7
    could you tell me there are differents between them ? thanks
    myemail:anqincmt@tom.com:
     
    nothing is verything.
    GeneralCorrect UTC Offsetmemberjheddings1 Dec '05 - 15:22 
    The offset for UTC needs to be added in, not subtracted. In the code, find lines 203, 246, & 271. Change "iHour -= iHrToTimeZone;" to "iHour += iHrToTimeZone;"
     
    Very useful utility!!
    Questionconverting to vb.net?membermichal_s_w1 Nov '05 - 8:31 
    this code is just what i need for my final project(i'm a student)
    is there any1 who knows how to convert it to vb.net?
    thanks so much,
    michal
    GeneralComparison didn't workmemberJWood3 May '05 - 16:25 
    I tried it but it appears that the sunrise is way off (45min), might it be a conversion from double to int?
    GeneralNorth/South & West/EastsussStanislav Khatsko24 Oct '04 - 3:27 
    Hello.
    I can't understand. There are ranges for Lantitude and Longitude between 0 and 180. And how can I enter following values:
     
    for example, 24.45 S , 18.06 E
    or 15.70 N , 5.37 W
     
    Which meridian and equator that example must be calculated from?
    I tried enter -24.45 (for South) and -18.06 (for East) but there only INTEGER values are allowed.
     
    Please help me!
    Thank you.
     

    GeneralInputmemberPiccinano25 Feb '03 - 3:36 
    Hi,
    in which format I must input the latitude and longitude in the program?
    Please, give me an example.
     
    Thanks.
     
    Piccinano
     

    GeneralRe: InputsussAnonymous21 Jun '03 - 14:03 
    45°1234m is 45.1234. That simple.
    GeneralRe: InputsussStanislav Khatsko24 Oct '04 - 3:32 
    >45°1234m
     
    Which meridian that coordinate is calculated from?
    If I have 45°1234 N or 45°1234 S or 45°1234 W or 45°1234 E
    how can I enter these examples?
     

    GeneralDaylight SavingsmemberDarroll Walsh9 Apr '02 - 4:42 
    This isn't really a bug but, it is something that some of us have to deal with. When I have perfected the code I will post it. the formulas are:
     
    AprilDate = (2+6 * thisYear - Math.floor (thisYear / 4) ) % 7 + 1;
    OctoberDate=   (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
     
    This is in JavaScript but it is easily converted.
     
    Darroll Walsh
    GeneralRe: Daylight SavingsmemberDarroll Walsh9 Apr '02 - 5:20 
    Here is the code for VC++
     
    // Add an hour if in daylight savinds
    // AprilDate = (2+6 * thisYear - Math.floor (thisYear / 4) ) % 7 + 1;
    // OctoberDate=   (31-( Math.floor (thisYear * 5 / 4) + 1) % 7);
     
    // set this bool in options for areas that aren't in daylight savings.
    bool m_bDaylightSavings = true;
    if( m_bDaylightSavings )
    {
          // April date
          int year = tTime.GetYear();
          int temp = floor( year /4 );
          int AprilDate = (2 + 6 * year - temp ) % 7 + 1;
          // October date
          temp = floor( year * 5 / 4 );
          int OctDate = ( 31 - ( temp + 1 ) % 7 );
     
          // BETWEEN APRIL AND OCTOBER WE ARE IN DAYLIGHT SAVINGS
          if( MyTime.GetMonth() > 4 && MyTime.GetMonth() < 10 )
          {
                   MyTime += CTimeSpan( 0,1,0,0);
          }
          else
          {
                   // IF IN APRIL
                   if( MyTime.GetMonth() == 4 )
                   {
                         if( MyTime.GetDay() >= AprilDate )
                         {
                                  MyTime += CTimeSpan( 0,1,0,0);
                         }
                   }
                   // IF IN OCTOBER
                   if( MyTime.GetMonth() == 10 )
                   {
                         if( MyTime.GetDay() >= OctDate )
                         {
                                  MyTime += CTimeSpan( 0,1,0,0);
                         }
                   }
          }              
    }
     
    Hope this helps someone;
     
    Signature not available do to your secutity settings. Press <CTRL><ALT><DEL> to fix this error.
    GeneralRe: Daylight SavingssussEzel324 Nov '03 - 2:24 
    This is not helping at all, If you want to know if dst is in effect in VC++ just code:
     
    if ( _daylight )
    {
    // do DST stuff..
    }

    GeneralRe: Daylight SavingssussKSharenkov11 Jan '05 - 18:02 
    _daylight is not says "is currently daylight savings used or not". it just tells has current time zone DST or not
    So it is not changing during the year.
    GeneralDosen't work ;(memberTutankhamen2 Jul '01 - 5:14 
    Confused | :confused:
    I found several troubles in your code.
     
    1st - demo project don't agree negative values.
    2nd:
     
    Now 2nd of July.
    In Moscow: SunRise: 4.51am Sunset: 10.19pm (Lat:56, Lon 38) - it's right.
    In Krasnodar: SunRise: 5.53am Sunset: 9.25pm (Lat:45, Lon 39) - it's wrong !!!
     


    GeneralRe: Dosen't work ;(membercraig.miller26 May '10 - 13:02 
    I've experienced the same problem. Even after fixing the basic errors, the fundamental algorithm doesn't correctly calculate sunrise/sunset times.
    QuestionWhat about height ?memberMiron Ophir30 Dec '00 - 3:35 
    The height above see level also should be taken into consideration.
    Generalconvert UTC to LOCALmemberBrian H21 Nov '00 - 9:51 
    Hi,
     
    I have since had to use my own code for a Utility Im
    writing for my fishing site(Uglybass.com), so I figured
    out how to convert quite easily to Local time... Just
    add the three lines given below to the bottom of all three function; GetSunrise(..) GetSunset(..) and GetSolarnoon(..) right before the line:
     
    CTime NewTime(time.GetYear(),time.GetMonth(),time.GetDay(),iHour,iMinute,iSecond);
     

    add:
     
    _tzset();
    int iHrToTimeZone = _timezone / 3600; //returns a difference value in seconds
    iHour -= iHrToTimeZone;
     
    Sorry, for the original sloppy article. I believe I was a
    little ticked at the people who didn't want to share this
    simple code!!! So I wrote it very quickly!!
     
    Enjoy!!!
     
    Brian

    GeneralCTimesussNorm Almond20 Jul '00 - 5:45 
    Replace CTime to COleDateTime for Y2K issues
    GeneralRe: CTimememberCrispy18 Dec '00 - 12:22 
    Don't you mean Y2036 issues? Wink | ;)

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

    Permalink | Advertise | Privacy | Mobile
    Web02 | 2.6.130523.1 | Last Updated 15 Dec 2000
    Article Copyright 2000 by Brian Heilman
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid