0

我正在将两个日期和时间字符串转换为,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

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

4

4 回答 4

1

试试这个代码...

    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);
于 2013-04-25T05:51:46.520 回答
1

试试这样

NSDate *mydate = [NSDate date];
NSTimeInterval secondsInEightHours = 4 * 60 * 60;
NSDate *dateEightHoursAhead = [mydate dateByAddingTimeInterval:secondsInEightHours];
于 2013-04-25T05:52:42.557 回答
1

如果 dateString 如下所示,这应该可以工作,则假定时区是您的本地时区。日期日志将采用 UTC

NSString *dateString = @"2011-11-21 11:20";

NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

NSDate * date = [dateFormatter dateFromString:dateString];
NSLog(@"%@",date);
于 2013-04-25T06:16:48.123 回答
1

请尝试此代码...

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];

    [dateFormatter1 setDateFormat:@"MM/dd/yyyy hh:mm a"];
    [dateFormatter1 setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    NSDate *myDate = [dateFormatter1 dateFromString:@"01/20/2015 11:00 pm"];
    NSLog(@"mydate is :%@",myDate);
    NSLog(@"DATE IS : %@",[dateFormatter1 stringFromDate:myDate]);

注意:时区取决于您当地的时区。

于 2013-04-25T08:07:36.687 回答