2014-03-04 36 views
-1

所以,我试图为日出和日落创建一个NSDate对象。我得到的日期是基于NSDatePicker,我从地图获取坐标,并从地图获取GPS的时区。NSDate和NSDateformatter错误的输出

我用这个代码来获取NSDate对象:https://github.com/MosheBerman/KosherCocoa-legacy 这一次得到的坐标:https://github.com/digdog/MapKitDragAndDrop 而这一次,以获得基于坐标时区:https://github.com/Alterplay/APTimeZones

现在我的物理位置在洛杉矶,我用来测试的日出和日落在丹麦回家了。

-(NSString *)sunriseDate{ 
    //Create the GeoLocation based on 'latitude' and 'longitude' (getting the from MapKitDragAndDrop) and 'location.timeZone' (getting that from APTimeZones). 
    GeoLocation *position = [[GeoLocation alloc] initWithName:@"position" andLatitude:latitude andLongitude:longitude andTimeZone:location.timeZone]; 

    AstronomicalCalendar *astronomicalCalender = [[AstronomicalCalendar alloc] initWithLocation:position]; 

    //daysBetween is the value from NSDatePicker 
    astronomicalCalender.workingDate = [NSDate dateWithTimeIntervalSinceNow:kSecondsInADay*[self daysBetween]]; 

    NSDate *sunriseDate = [astronomicalCalender sunrise]; 
    NSLog(@"Sunrise time: %@", sunriseDate); 
    //This spits out: Sunrise time: 2014-03-05 06:09:53 AM +0000 which is the right time. 
    NSDateFormatter *sunriseTime = [[NSDateFormatter alloc] init]; 
    [sunriseTime setDateFormat:@"HH:mm:ss"]; 

    NSString *sunriseString = [sunriseTime stringFromDate:sunriseDate]; 
    NSLog(@"Sunrisestring: %@", sunriseString); 
    //This spits out: 10:09:53 PM. 
    return sunriseString; 

} 

为什么会发生这种情况,谁能给我一个解决方案呢?

回答

1

[sunriseTime setDateFormat:@"yyyy-MM-dd hh:mm:ss a EEEE"];

,而不是为了任何人谁可能会再次陷入同样的​​事情。

我在github上发现了一个库https://github.com/Alterplay/APTimeZones,它帮助我根据坐标确定时区。

然后我用

[sunriseTime setTimeZone:location.timeZone]; 

这引出正确的时间时区。

希望这有助于任何人!

0

您需要正确匹配输入格式。

您可能只对时间感兴趣,但NSDateFormatter并不在意。 NSDate从来就不是一个时间。这是一个时间点,也包括日期。没有日期和时间部分,它不起作用。

此外,这可能是Stack Overflow上最常见的问题之一。任何其他NSDate到NSString(反之亦然)的问题将回答这个问题。

你的日期格式应该是...

@"YYYY-MM-dd hh:mm:ss a EEEE" 

我相信。反正就是这样。

+0

我找不到任何东西,并相信我,我一直在寻找。我无法从这个答案中得到任何东西。除了如何显示和/或iPhone的时区是什么。如果您可能可以指向我自从我自己的搜索以来正在讨论的任何线程的方向有很短的时间.. (EEE是白天,zzzz是时区) – 4FunAndProfit

0

这吐出来了:10:09:53 PM。这是您的时区正确的当地时间,与格林尼治时间相差8小时日出时间:2014年03月05日06:09:53上午+0000。就这样。你有一个德国人醒来的晚上。

+0

确切的,但我需要吐出它的时间为尊重时区。 – 4FunAndProfit

0

您可以尝试使用这样的:[sunriseTime setDateFormat:@"HH:mm:ss"];

+0

我试过了。这只返回时区ekstra,它不会改变输出以匹配坐标的正确时间,''hh:mm:ss''部分打印完全一样的东西。 – 4FunAndProfit