iphone - 将 NSString 转换为 NSDate

标签 iphone ios nsdateformatter datetime-format

我正在将两个日期和时间字符串转换为 NSDate 但我总是得到错误的时间,但是得到正确的日期,我不知道为什么 xcode 给出错误的日志消息,我似乎有很多NSDate 代码但都不起作用,这个在我更改日期格式时起作用,告诉我如何处理时间格式

     NSDate * date;
    //Assume dateString is populated and of format NSString * dateString =@"2011-11-21 11:20";
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    NSString *dateString =[NSString stringWithFormat:@"%@ %@", socialEvent.SocialEventsDC_EventDate,socialEvent.SocialEventsDC_EventStartTime];
    NSLog(@"%@ %@",socialEvent.SocialEventsDC_EventDate,socialEvent.SocialEventsDC_EventStartTime);

    [dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm a"];
    if (dateString != nil)  {
        date = [dateFormatter dateFromString:dateString];
//        [date release];
    }

    NSLog(@"%@",date);

我的日志信息是

2013-04-25 10:45:04.417 BNI UK & Ire[450:5203] 01/20/2015 11:00 PM
2013-04-25 10:45:09.679 BNI UK & Ire[450:5203] 2015-01-20 07:00:00 +0000

虽然我的时间是11:00,但我的时间总是7:00:00,请帮帮我

最佳答案

试试这个代码...

    NSString * dateString =@"2011-11-21 11:20";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    // [formatter setTimeZone:[NSTimeZone localTimeZone]];

    NSDate *datTemp = [formatter dateFromString:dateString];
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:datTemp];
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:datTemp];
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:datTemp] autorelease];
    NSLog(@"\n\n\n Destination date is:- %@",destinationDate);

关于iphone - 将 NSString 转换为 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16207232/

相关文章:

iphone - 在 iPhone 上创建新 NSConnection 的成本

iphone - iPhone 上的视网膜显示屏图像

iphone - 如何向 Google map 上的信息窗口添加组合框和按钮?

ios - 格式字符串未使用数据参数

ios - 如何在 Xcode 中使用没有 CocoaPod 的任何框架

swift - 计算从两个 UIDatePickers Swift 4 中选择的日期值

ios - iOS 中的日期格式/错误处理问题

iphone - 如何使用 NSDateFormatter 解析 Obj-C 中的时间格式?

iphone - 保持向后兼容 iPhone OS 2.2.1

ios - 解析错误代码 206 : Cannot modify user (Parse Server)