Display Sunrise and Sunset Time Using C-Sharp and MySQL Database

In this tutorial, we demonstrate you on how to display visitor’s sunrise and sunset time based on their IP address using PHP programming languages and IP2Location MySQL database. In this tutorial, we use the IP2Location LITE database to lookup country of origin from the visitor’s IP address. Free databases are available for download at IP2Location LITE database.

Step 1: Download IP2Location LITE database, unzip the file follow the instruction in order to create database table. Please refer to DB11 LITE for further information.

Step 2: Download the demo project at Display sunrise and sunset time using C sharp and include into your C Sharp project.

Below are the steps to set up the database for both IPv4 and IPv6 data and the sample codes

Calculation for sunrise and sunset time

	protected string calculate(DateTime date, int set_rise, double offset)
	{
		//Convert longitude into hour value
		double long_hour = longitude / 15;
		double t = 0;

		//sunset = 0, sunrise = 1
		//calculate approximate time
		if (set_rise == 1)
		{
			t = Convert.ToDouble(date.DayOfYear) + ((6 - long_hour) / 24);
		}
		else if (set_rise == 0)
		{
			t = Convert.ToDouble(date.DayOfYear) + ((18 - long_hour) / 24);
		}

		//Calculate Sun's mean anomaly time
		double mean = (0.9856 * t) - 3.289;

		//Calculate Sun's true longitude
		double sun_true_long = mean + (1.916 * Math.Sin(mean * D2R)) + (0.020 * Math.Sin(2 * mean * D2R)) + 282.634;
		if (sun_true_long > 360)
			sun_true_long = sun_true_long - 360;
		else if (sun_true_long < 0)
			sun_true_long = sun_true_long + 360;

		//Calculate Sun's right ascension
		double right_ascension = R2D * Math.Atan(0.91764 * Math.Tan(sun_true_long * D2R));
		if (right_ascension > 360)
			right_ascension = right_ascension - 360;
		else if (right_ascension < 0)
			right_ascension = right_ascension + 360;

		//Adjust right ascension value to be in the same quadrant as Sun's true longitude
		double Lquadrant = (Math.Floor(sun_true_long / 90)) * 90;
		double RAquadrant = (Math.Floor(right_ascension / 90)) * 90;
		right_ascension = right_ascension + (Lquadrant - RAquadrant);

		//Convert right ascension value into hours
		right_ascension = right_ascension / 15;

		//Calculate Sun's declination
		double sinDec = 0.39782 * Math.Sin(sun_true_long * D2R);
		double cosDec = Math.Cos(Math.Asin(sinDec));

		//Setting Sun's zenith value
		double zenith = 90 + (50 / 60);

		//Calculate Sun's local hour angle
		double cosH = (Math.Cos(zenith * D2R) - (sinDec * Math.Sin(latitude * D2R))) / (cosDec * Math.Cos(latitude * D2R));

		if (cosH > 1)
		{
			Response.Write("Sun never rises on this day. " + date.Year + "/" + date.Month + "/" + date.Day + "
"); } else if (cosH < -1) { Response.Write("Sun never sets on this day. " + date.Year + "/" + date.Month + "/" + date.Day + "
"); } //Calculate and convert into hour of sunset or sunrise double hour = 0; if (set_rise == 1) { hour = 360 - R2D * Math.Acos(cosH); } else if (set_rise == 0) { hour = R2D * Math.Acos(cosH); } hour = hour / 15; //Calculate local mean time of rising or setting double local_mean_time = hour + right_ascension - (0.06571 * t) - 6.622; //Adjust time to UTC double utc = local_mean_time - long_hour; //Convert time from UTC to local time zone double local_time = utc + offset; if (local_time > 24) local_time = local_time - 24; else if (local_time < 0) local_time = local_time + 24; //Convert the local_time into time format int s_hour = Convert.ToInt32(Math.Floor(local_time)); int s_minute = Convert.ToInt32(Math.Floor((local_time - s_hour) * 60)); if (s_minute < 10) return s_hour + ":0" + s_minute; else return s_hour + ":" + s_minute; }

Retrieving data

	public static string[] Get_Data(string query)
	{
	//Database connection string, replace lower capital with MySQL settings
	string db_con_string = "SERVER=server;DATABASE=database;UID=userid;PASSWORD=password;";
		using (MySqlConnection con = new MySqlConnection(db_con_string))
		{
			using (MySqlCommand cmd = new MySqlCommand())
			{
				cmd.CommandText = query;
				using (MySqlDataAdapter sda = new MySqlDataAdapter())
				{
					cmd.Connection = con;
					sda.SelectCommand = cmd;
					using (DataSet ds = new DataSet())
					{
						DataTable dt = new DataTable();
						sda.Fill(dt);
						object timezone = dt.Rows[0]["time_zone"];
						object country_code = dt.Rows[0]["country_code"];
						object latitude = dt.Rows[0]["latitude"];
						object longitude = dt.Rows[0]["longitude"];
						string[] data = { Convert.ToString(timezone), Convert.ToString(country_code), Convert.ToString(latitude), Convert.ToString(longitude) };
						return data;
					}
				}
			}
		}
	}

Converting IP address to IP number

	public long ip_to_number(string ip_addr)
		{
		string[] ip_Sblock;
		int[] ip_block = new int[4];
		string[] separator = { "." };

		ip_Sblock = ip_addr.Split(separator, StringSplitOptions.None);
		for (int i = 0; i <= 3; i++)
		{
			ip_block[i] = Convert.ToInt32(ip_Sblock[i]);
		}

	return ip_block[0] * 16777216 + ip_block[1] * 65536 + ip_block[2] * 256 + ip_block[3];
}

Calculation for sunrise and sunset time

protected string calculate(DateTime date, int set_rise, double offset)
	{
		//Convert longitude into hour value
		double long_hour = longitude / 15;
		double t = 0;

		//sunset = 0, sunrise = 1
		//calculate approximate time
		if (set_rise == 1)
		{
			t = Convert.ToDouble(date.DayOfYear) + ((6 - long_hour) / 24);
		}
		else if (set_rise == 0)
		{
			t = Convert.ToDouble(date.DayOfYear) + ((18 - long_hour) / 24);
		}

		//Calculate Sun's mean anomaly time
		double mean = (0.9856 * t) - 3.289;

		//Calculate Sun's true longitude
		double sun_true_long = mean + (1.916 * Math.Sin(mean * D2R)) + (0.020 * Math.Sin(2 * mean * D2R)) + 282.634;
		if (sun_true_long > 360)
			sun_true_long = sun_true_long - 360;
		else if (sun_true_long < 0)
			sun_true_long = sun_true_long + 360;

		//Calculate Sun's right ascension
		double right_ascension = R2D * Math.Atan(0.91764 * Math.Tan(sun_true_long * D2R));
		if (right_ascension > 360)
			right_ascension = right_ascension - 360;
		else if (right_ascension < 0)
			right_ascension = right_ascension + 360;

		//Adjust right ascension value to be in the same quadrant as Sun's true longitude
		double Lquadrant = (Math.Floor(sun_true_long / 90)) * 90;
		double RAquadrant = (Math.Floor(right_ascension / 90)) * 90;
		right_ascension = right_ascension + (Lquadrant - RAquadrant);

		//Convert right ascension value into hours
		right_ascension = right_ascension / 15;

		//Calculate Sun's declination
		double sinDec = 0.39782 * Math.Sin(sun_true_long * D2R);
		double cosDec = Math.Cos(Math.Asin(sinDec));

		//Setting Sun's zenith value
		double zenith = 90 + (50 / 60);

		//Calculate Sun's local hour angle
		double cosH = (Math.Cos(zenith * D2R) - (sinDec * Math.Sin(latitude * D2R))) / (cosDec * Math.Cos(latitude * D2R));

		if (cosH > 1)
		{
			Response.Write("Sun never rises on this day. " + date.Year + "/" + date.Month + "/" + date.Day + "
"); } else if (cosH < -1) { Response.Write("Sun never sets on this day. " + date.Year + "/" + date.Month + "/" + date.Day + "
"); } //Calculate and convert into hour of sunset or sunrise double hour = 0; if (set_rise == 1) { hour = 360 - R2D * Math.Acos(cosH); } else if (set_rise == 0) { hour = R2D * Math.Acos(cosH); } hour = hour / 15; //Calculate local mean time of rising or setting double local_mean_time = hour + right_ascension - (0.06571 * t) - 6.622; //Adjust time to UTC double utc = local_mean_time - long_hour; //Convert time from UTC to local time zone double local_time = utc + offset; if (local_time > 24) local_time = local_time - 24; else if (local_time < 0) local_time = local_time + 24; //Convert the local_time into time format int s_hour = Convert.ToInt32(Math.Floor(local_time)); int s_minute = Convert.ToInt32(Math.Floor((local_time - s_hour) * 60)); if (s_minute < 10) return s_hour + ":0" + s_minute; else return s_hour + ":" + s_minute; }

Retrieving data

	public static string[] Get_Data(string query)
	{
		//Database connection string, replace lower capital with MySQL settings
		string db_con_string = "SERVER=server;DATABASE=database;UID=userid;PASSWORD=password;";
		using (MySqlConnection con = new MySqlConnection(db_con_string))
		{
			using (MySqlCommand cmd = new MySqlCommand())
			{
				cmd.CommandText = query;
				using (MySqlDataAdapter sda = new MySqlDataAdapter())
				{
					cmd.Connection = con;
					sda.SelectCommand = cmd;
					using (DataSet ds = new DataSet())
					{
						DataTable dt = new DataTable();
						sda.Fill(dt);
						object timezone = dt.Rows[0]["time_zone"];
						object country_code = dt.Rows[0]["country_code"];
						object latitude = dt.Rows[0]["latitude"];
						object longitude = dt.Rows[0]["longitude"];
						string[] data = { Convert.ToString(timezone), Convert.ToString(country_code), Convert.ToString(latitude), Convert.ToString(longitude) };
						return data;
					}
				}
			}
		}
	}

Converting IP address to IP number

	public System.Numerics.BigInteger ip_to_number(string ip_addr)
	{
		System.Net.IPAddress address;
		System.Numerics.BigInteger ipnum = 0;

		if (System.Net.IPAddress.TryParse(ip_addr, out address))
		{
			byte[] addrBytes = address.GetAddressBytes();

			if (System.BitConverter.IsLittleEndian)
			{
				System.Collections.Generic.List byteList = new System.Collections.Generic.List(addrBytes);
				byteList.Reverse();
				addrBytes = byteList.ToArray();
			}

			if (addrBytes.Length > 8)
			{
				//IPv6
				ipnum = System.BitConverter.ToUInt64(addrBytes, 8);
				ipnum <<= 64;
				ipnum += System.BitConverter.ToUInt64(addrBytes, 0);
			}
			else
			{
				//IPv4
				ipnum = System.BitConverter.ToUInt32(addrBytes, 0);
			}
		}
		return ipnum;
	}

Was this article helpful?

Related Articles