Friday, June 20, 2014

Sunrise and Sunset in C#

Is there a way in C# to calculate given a latitude and longitude when the sun will set and rise for a given day?

Yes, i used NAA java-script code and converted C# code from here.  

I tested it against:

http://www.timeanddate.com/sun/usa/seattle

http://www.esrl.noaa.gov/gmd/grad/solcalc/

static double JD = 0;
static int zone = -8// Seattle time Zone
static double latitude = 47.6// Seattle lat
static double longitude = -122.32// Seattle lon 
static bool dst = true// Day Light Savings 
static DateTime date = DateTime.Today;
 
static void Main(string[] args)
{
    JD = Util.calcJD(date);  //OR   JD = Util.calcJD(2014, 6, 1);
    double sunRise = Util.calcSunRiseUTC(JD, latitude, longitude);
    double sunSet = Util.calcSunSetUTC(JD, latitude, longitude);
    System.Console.WriteLine(Util.getTimeString(sunRise, zone, JD, dst));
    System.Console.WriteLine(Util.getTimeString(sunSet, zone, JD, dst));
    System.Console.WriteLine("");
    System.Console.WriteLine(Util.getDateTime(sunRise, zone, date, dst).Value.ToString());
    System.Console.WriteLine(Util.getDateTime(sunSet, zone, date, dst).Value.ToString());
}

Download VS project here

4 comments:

  1. Hi, it works for Moscow, but for Guadalajara, Mexico - LAT=20, LNG=-103 values are not correct, I get sunrise at {14.01.2015 12:26:58} in Mexico!

    SunTimes.Instance.CalculateSunRiseSetTimes(20.6667, -102, DateTime.Now, ref rise, ref set, ref isRise, ref isSet);

    Any Suggestions?

    ReplyDelete
    Replies
    1. Fixes bellow:
      Estimado Alexei (Увыжаемый тёзка =) вам надо настроить правильно параметры для Guadalajarы)
      usa estos parametros:

      static int zone = -7; // Guadalajara
      static double latitude = 20.666; //Guadalajara
      static double longitude = -103;
      static bool dst = true; // Day Light Savings
      static DateTime date = DateTime.Today;
      /*
      google results:
      nice search:
      https://www.google.ru/search?q=sunrise+guadalajara+mexico&gws_rd=cr&ei=ifuVVvj_BeawygPXv5go#newwindow=1&q=sunrise+sunset+guadalajara+mexico
      13.01.2016 7:31:47
      13.01.2016 18:30:48
      */

      Delete

  2. THANK YOU, very good algorithm, Sunset sunrise for Moscow must be with those values:

    static double JD = 0;
    static int zone = 2; // Seattle time Zone
    static double latitude = 55.7522222; // Seattle lat
    static double longitude = 37.6155556; // Seattle lon
    static bool dst = true; // Day Light Savings
    static DateTime date = DateTime.Today;
    /*
    Moscow results
    13.01.2016 8:52:22
    13.01.2016 16:23:18
    Very GOOD!
    google shows those values>
    8:51 - 16:24

    **/

    ReplyDelete
  3. I dont understand why I have to setup wrong zone parameter, for example: Moscow: 2 (instead 3) , Guadalajara -7 (instead -6)

    ReplyDelete