想知道原理,可以了解初中地理。直接上代码。
-(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;
}
}