|
MoonPhase Function
Listing 1. Suppose that as part of analyzing sales data, you must calculate the percentage of the 29.5-day lunar cycle for a given date/time value. You could write the function in C# as shown here. [Microsoft.SqlServer.Server.SqlFunction(Name = "MoonPhase")]
public static double MoonPhase(DateTime inDate)
{
// BACKGROUND: On average, the Moon goes through its phases in
// 29.53 days (i.e., New Moon to New Moon). I stress
// "average" because orbital mechanics makes this
// shorter for some months, and longer for others.
// May 26, 1979 is a good Epoch because the New Moon began at
// exactly 12:00 AM UTC
// Subtract the Epoch from the DateTime passed in (assumed UTC)
TimeSpan sinceEpoch =
inDate - new DateTime(1979, 5, 26, 0, 0, 0, 0, DateTimeKind.Utc);
// Calculate and return the percentage of the current phase
return (sinceEpoch.TotalDays % 29.53D) / 29.53D;
}
|