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

No comments:

Post a Comment