iphone - NSDate 格式输出错误的日期

标签 iphone objective-c nsdate nsdateformatter

我有一个 NSString(例如“2011-04-12 19:23:39”),我将其格式化为 NSDate 的操作如下:

[inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date = [inputFormatter dateFromString:newDateString];

但是当我 nslog 日期时它输出的是这样的:

2011-04-12 23:23:39 +0000

大约休息了 4 个小时。我错过了什么吗?可能是时区问题?

最佳答案

简而言之,除非另有说明,否则返回的日期是格林威治标准时间。您可以设置时区以获得正确的日期。如果您计划在应用程序中使用日期来设置任何内容(如 localNotification 时间或事件),您将需要对日期做一些特殊的事情,因为如果您在 iPhone 中设置日期,它将被设置为 GMT 时间并且将关闭几个小时。 (在你的情况下是 4 小时)。我做的正是我刚刚在我的一个应用程序中描述的事情。

我试图让这个在没有休息时间的情况下正常工作,结果一团糟。弄清楚这是一个巨大的 PITA,但它现在正在工作。我复制、粘贴和编辑了我的代码以供分享。同样,它很乱,但它有效! pickerChanged 正在从 UIDatePicker 获取信息

使用下面的代码。要回答您的问题,您可以停在“destinationDate”。这将返回给您当前时区的更正时间。我只是提供了额外的内容,以防您尝试在某处使用电话中的日期。

注意:举个简单的例子,我将事件提醒放在与日期选择器相同的功能中,你不会想要这样做,否则每次轮子在日期选择器中滚动时你都会设置很多提醒。

代码如下。

 - (void)pickerChanged:(id)sender
    {

        NSLog(@"value: %@",[sender date]);

        NSDate* date= [sender date]; 
        NSDateFormatter *formatter=[[[NSDateFormatter alloc]init]autorelease]; 
        [formatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
        [formatter setTimeZone:[NSTimeZone systemTimeZone]];

        [formatter setTimeStyle:NSDateFormatterLongStyle]; 

        NSString *dateSelected =[formatter stringFromDate:date]; 

        NSString *timeZone = [dateSelected substringFromIndex:12];



    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    //here we have to get the time difference between GMT and the current users Date (its in seconds)
        NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:date];

    //need to reverse offset so its correct when we put it in the calendar
        correctedTimeForCalendarEvent = destinationGMTOffset + (2*(-1*destinationGMTOffset));

    //date to enter into calendar (we will use the correctedTimeForCalendarEvent to correct the time otherwise it will be off by a few hours )
       NSDate * destinationDate = [[[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:date] autorelease];
        NSDate * dateForReminder = destinationDate;
        // return destinationDate;
        NSLog(@"value: %@ - %@",destinationDate,dateForReminder);

//DO NOT put this code in this same function this is for a quick example only on StackOverflow
//otherwise you will have reminders set everytime the users scrolled to a different time
    //set event reminder
    //make sure to import EventKit framework

        EKEventStore *eventDB = [[[EKEventStore alloc] init]autorelease];
        EKEvent *myEvent  = [EKEvent eventWithEventStore:eventDB];
        NSString * eventTitle = [NSString stringWithFormat:@"%@ - %@",app.dealerBusinessName,serviceOrComments.text];
        myEvent.title = eventTitle;

    //double check date one more time
        NSLog(@"value: %@",destinationDate);

    //set event time frame (1 hour) the "initWithTimeInterval" is where we account for the users timezone by adding the correctedTime from GMT to the calendar time ( so its not off by hours when entering into calendar)
        myEvent.startDate = [[[NSDate alloc] initWithTimeInterval:correctedTimeForCalendarEvent sinceDate:destinationDate ]autorelease];
        myEvent.endDate   = [[[NSDate alloc] initWithTimeInterval:3600 sinceDate:myEvent.startDate]autorelease];
        myEvent.allDay = NO;

    //set event reminders 1 day and 1 hour before
        myAlarmsArray = [[[NSMutableArray alloc] init] autorelease];
        EKAlarm *alarm1 = [EKAlarm alarmWithRelativeOffset:-3600]; // 1 Hour
        EKAlarm *alarm2 = [EKAlarm alarmWithRelativeOffset:-86400]; // 1 Day
        [myAlarmsArray addObject:alarm1];
        [myAlarmsArray addObject:alarm2];
        myEvent.alarms = myAlarmsArray;



        [myEvent setCalendar:[eventDB defaultCalendarForNewEvents]];

        NSError *err;

        [eventDB saveEvent:myEvent span:EKSpanThisEvent error:&err]; 

        if (err == noErr) {
            //no error, but do not show alert because we do that below.
        }

    }

关于iphone - NSDate 格式输出错误的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6229024/

相关文章:

ios - 使用自动布局修复自定义 UITableViewCell

ios - 我试图让我的应用程序在达到 9 :00 UTC time every day 时弹出 viewControllers

iphone - geocodeAddressString无法识别的选择器错误处理结果

iphone - 将 HTML 解析为 XML 的最佳方式

iphone - 在呈现 View 之前如何设置 UIImageView 的图像?

ios - 如何获得关系的另一面

ios - 将 UITableViewCell 的背景颜色设置为图案图像

iphone - 从 unix 时间戳获取人类可读的相对时间和日期?

ios - 代码未在 UILabel 中从 Parse.com 检索/显示日期

iphone - 无法在设备上测试 iOS 应用内购买,只有模拟器