iOS 根据经纬度计算日出和日落时间

这段代码展示了如何在iOS中根据经纬度信息计算出当天的日出和日落时间,利用了日期、地理坐标和天文算法。对于经度小于1的地方,假设日出时间为7:00,日落时间为17:00。否则,它会根据当前日期和地球位置进行精确计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

想知道原理,可以了解初中地理。直接上代码。

-(NSString*)gettimewith:(double) lat with:(double )lng with:(BOOL)isSunRise withTime:(NSString*)dayTime{

    if (lat<1&&isSunRise==YES) {

        

        return [NSString stringWithFormat:@"%@ 07:00",dayTime];

        

    }else if (lat<1&&isSunRise==NO) {

        

        return [NSString stringWithFormat:@"%@ 17:00",dayTime];

    }else{

        NSDate *now1 = [NSDate date];

            //实例化一个NSDateFormatter对象

        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

                //设定时间格式

        [dateFormatter setDateFormat:@"yyyy-MM-dd"];

        NSDate *oldDate1 = [dateFormatter dateFromString: @"2020-01-01"];

        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

        unsigned int unitFlags = NSCalendarUnitDay;

        NSDateComponents *comps = [gregorian components:unitFlags fromDate:oldDate1  toDate:now1  options:0];

        NSInteger dayCount=[comps day];

        

        double ut0 = 180;

        double utStart = 0;

        double h =sin(-0.833 * M_PI/180);

        for(; abs(utStart - ut0) >= 0.1; ut0 = utStart) {

            double t = (dayCount + ut0 / 360) / 36525; // 世纪数

            double L = 280.460 + 36000.777 * t; // 太阳平均黄径

            double G = (357.528 + 35999.050 * t)* M_PI/180; // 太阳平近点角

            double lamda = (L + 1.915 * sin(G) + 0.020 * sin(2 * G))* M_PI/180; // 太阳黄道经度

            double epc = (23.4393- 0.0130 * t)* M_PI/180; // 地球倾角

            double sigam = asin(sin(epc) * sin(lamda));// 太阳的偏差

            // 格林威治时间太阳时间角

            double gha = ut0 - 180 - 1.915 * sin(G) - 0.020 * sin(2 * G)

                                + 2.466 * sin(2 * lamda) - 0.053 * sin(4 * lamda);

                        // 修正值e

            double e = (acos((h - tan(lat) * tan(sigam)))*180/M_PI);

            utStart = ut0 - gha - lng + (isSunRise ? -e : e);

        }

        int zone = (int) (lng / 15 + (lng >= 0 ? 1 : -1));// 当前时区

        float time=utStart / 15 + zone;

        NSString * subStr=[NSString stringWithFormat:@"%f",time];

        NSArray * subArr=[subStr componentsSeparatedByString:@"."];

        NSString * subStr1=[NSString stringWithFormat:@"0.%@",subArr[1]];

        NSString * second=[NSString stringWithFormat:@"%f",[subStr1 doubleValue]*60];

        NSString * sum=[NSString stringWithFormat:@"%@ 0%@:%d",dayTime,subArr[0],[second intValue]];

        NSLog(@"获取到的日出和日落----%f-%@",time,sum);

        return sum;

    }

    

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值