65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 类用于计算日出日落时间

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.28/5 (17投票s)

2008 年 9 月 13 日

公共领域

1分钟阅读

viewsIcon

159782

downloadIcon

4906

一个用于计算日出和日落时间的类,实现为线程安全的单例

引言

这个简单的 C# 单例类可以计算给定日期的日出和日落时间。

背景

在寻找一个简单且体面的计算给定日期日出和日落时间的实现方案时,并且尝试了几种要么过于复杂难以迁移到 C#,要么根本无法工作的实现方案后,我找到一个简单但可用的 JavaScript 实现 在此

我将代码迁移到 C#,并对其进行了一些调整,以提供准确的计算。此外,我将其封装为单例类(假设对于此类不需要多个实例),并添加了锁到主要的计算方法中,以便使其线程安全(通过阻塞)。

Using the Code

单例类 SunTimes 可以从代码中的任何位置通过调用 SunTimes.Instance 来调用。

该类包含一个名为 CalculateSunRiseSetTimes() 的单个方法,并具有一个重载。您只需调用此方法,并为其提供三个输入参数:所需位置的纬度和经度,以及要计算的日期。此外,您需要传递四个(4)输出(ref)参数:riseTime (日出时间)、setTime (日落时间)、isSunrise (当天太阳会升起吗?)和 isSunset (当天太阳会落下吗?)。

该方法返回一个布尔值,指示计算是否成功(如果时区和经度不兼容,则会失败)。

这是一个类用法的示例

...

DateTime date = DateTime.Today;
bool isSunrise = false;
bool isSunset = false;
DateTime sunrise = DateTime.Now;
DateTime sunset = DateTime.Now;

// Print out the Sunrise and Sunset times for the next 20 days
for (int i=0; i<20; i++)
{
                                                // Coordinates of Tel-Aviv
     SunTimes.Instance.CalculateSunRiseSetTimes(new SunTimes.LatitudeCoords
                                   (32, 4, 0, SunTimes.LatitudeCoords.Direction.North),
                                                new SunTimes.LongitudeCoords
                                   (34, 46, 0, SunTimes.LongitudeCoords.Direction.East),
                                                date, ref sunrise, ref sunset, 
			                     ref isSunrise, ref isSunset);

     Debug.Print(date + '': Sunrise @'' + sunrise.ToString('HH:mm') + ''  
				Sunset @'' + sunset.ToString(''HH:mm''));

     date = date.AddDays(1); // Move to the next day
}

...

关注点

这个实现并不特别花哨,设计也不够完美,但是 - 它完成了工作(至少就我测试过的而言)。如果您检测到任何实际的错误,我很乐意收到任何评论(请不要评论其设计,除非您检测到实际的错误)。

历史

  • 2008-09-14:上传了类实现
© . All rights reserved.