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:

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(Util.getDateTime(sunRise, zone, date, dst).Value.ToString());
    System.Console.WriteLine(Util.getDateTime(sunSet, zone, date, dst).Value.ToString());

Download VS project here

1 comment:

  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?