NSDate和NSDateformatter输出错误

时间:2014-03-04 09:07:10

标签: ios timezone nsdate nsdateformatter

所以,我正在尝试为日出和日落创建一个NSDate对象。我根据NSDatePicker获取日期,我从地图获取坐标,然后从地图上获取GPS的时区。

我使用此代码获取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;

}

为什么会发生这种情况,任何人都可以给我一个解决方案吗?

5 个答案:

答案 0 :(得分:1)

任何可能偶然发现同样事物的人。

我在github https://github.com/Alterplay/APTimeZones上找到了一个帮助我根据坐标确定时区的库。

然后我用了

[sunriseTime setTimeZone:location.timeZone];

这为时区提供了合适的时间。

希望这对任何人都有帮助!

答案 1 :(得分:0)

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

您可能只对时间感兴趣,但NSDateFormatter并不关心。 NSDate永远不会是一个时间。这是一个时间点,所以也包括日期。没有日期和时间部分,它不起作用。

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

您的日期格式应为......

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

我相信。无论如何都是这样的。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

正如Fogmeister所说,你应该在创建NSDateFormatter时包含时区。在Apple's Docs, Data Formatting Guide获取战利品:

  

固定格式   要为日期格式化程序指定自定义固定格式,请使用setDateFormat:。格式字符串使用Unicode技术标准#35中的格式模式。

Unicode官方网站:

http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

答案 4 :(得分:0)

您可以尝试使用此功能:[sunriseTime setDateFormat:@"yyyy-MM-dd hh:mm:ss a EEEE"];

而不是[sunriseTime setDateFormat:@"HH:mm:ss"];