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