Ios NSDate和NSDateformatter输出错误

Ios NSDate和NSDateformatter输出错误,ios,timezone,nsdate,nsdateformatter,Ios,Timezone,Nsdate,Nsdateformatter,因此,我试图为日出和日落创建一个NSDate对象。我根据NSDatePicker获取日期,从地图获取坐标,从地图的GPS获取时区 我使用此代码获取NSDate对象: 这是一个获取坐标的方法: 这是一个基于坐标的时区 现在我的实际位置在洛杉矶,我用来测试的日出和日落都在丹麦的家里 -(NSString *)sunriseDate{ //Create the GeoLocation based on 'latitude' and 'longitude' (getting the from M

因此,我试图为日出和日落创建一个
NSDate
对象。我根据
NSDatePicker
获取日期,从地图获取坐标,从地图的GPS获取时区

我使用此代码获取
NSDate
对象: 这是一个获取坐标的方法: 这是一个基于坐标的时区

现在我的实际位置在洛杉矶,我用来测试的日出和日落都在丹麦的家里

-(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;

}

为什么会发生这种情况?有人能给我一个解决方案吗?

您需要正确匹配输入格式

您可能只对时间感兴趣,但NSDateFormatter不关心。日期永远不只是时间。这是一个时间点,因此也包括日期。如果没有日期和时间部分,它将无法工作

此外,这可能是有关堆栈溢出的最常被问到的问题之一。任何其他NSDate到NSString(或反之亦然)的问题都将回答此问题

你的日期格式应该是

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

我相信。反正是这样的。

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

正如Fogmeister所说,在创建NSDateFormatter时,你应该包括时区。在以下位置获取战利品:

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

Unicode官方网站:


您可以尝试使用以下内容:
[sunriseTime setDateFormat:@“yyyy-MM-dd hh:MM:ss a EEEE”]


而不是
[sunriseTime setDateFormat:@“HH:mm:ss”]

给任何可能遇到同样事情的人

我在github上找到了一个库,它帮助我根据坐标确定时区

然后我用

[sunriseTime setTimeZone:location.timeZone];
这为时区提供了正确的时间


希望这对任何人都有帮助

没错,但我需要在时间里把它吐出来,因为我找不到任何东西,相信我,我一直在寻找。我无法从这个答案中得到任何东西。。除了如何显示和/或iPhone所在的时区。如果你能给我指一下你所说的任何一条线索的方向,因为我自己的搜索结果很短。。(EEE代表白天,ZZZ代表时区)我试过这个。这只返回时区ekstra,它不会改变输出以匹配坐标的正确时间,“hh:mm:ss”部分打印出完全相同的内容。