Ios 需要有关将字符串转换为日期的帮助吗

Ios 需要有关将字符串转换为日期的帮助吗,ios,objective-c,nsdate,nsdateformatter,Ios,Objective C,Nsdate,Nsdateformatter,我正在将字符串转换为实际的日期对象,但我得到了不同的行为 字符串=01-10-2014上午11:36 是我试图转换的实际值,但得到这个值 2014-10-01 18:36:00+0000 有什么问题吗?问题在于显示问题 您正在使用默认的日期格式化程序打印日期(NSLog使用描述方法) 时间以UTC(GMT)显示,看起来您处于时区-0700。时间以时区偏移0000显示 系统中的日期/时间基于GMT时间,这样可以跨时区和地球上任何地方比较时间。系统中的时间在同一时间是相同的 使用日期格式化程序以所需

我正在将
字符串
转换为实际的日期对象,但我得到了不同的行为

字符串=01-10-2014上午11:36

是我试图转换的实际值,但得到这个值

2014-10-01 18:36:00+0000


有什么问题吗?

问题在于显示问题

您正在使用默认的日期格式化程序打印日期(NSLog使用描述方法)

时间以UTC(GMT)显示,看起来您处于时区-0700。时间以时区偏移0000显示

系统中的日期/时间基于GMT时间,这样可以跨时区和地球上任何地方比较时间。系统中的时间在同一时间是相同的

使用日期格式化程序以所需格式获取日期/时间

示例代码:

- (void) dateConverter{
    NSString *string = [NSString stringWithFormat:@"%@ %@", [[self dates]objectAtIndex:0], [times objectAtIndex:0]]; // string = 01-10-2014 11:36 AM;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
    [dateFormatter setLocale:[NSLocale currentLocale]];
    NSDate *date = [[NSDate alloc] init];

    date = [dateFormatter dateFromString:string];
    NSLog(@"dateFromString = %@", date); // 2014-10-01 18:36:00 +0000

    NSTimeInterval timeInterval = [date timeIntervalSince1970];
    NSLog(@"dateFromString = %f", timeInterval); // 1412188560.000000
}
输出:

dateString=01-10-2014上午11:36
dateFromString=2014-10-01 15:36:00+0000
显示日期=2014年10月1日上午11:36


注意:您可以提供自己的日期格式,以获得您想要的格式。

在我看来非常正常。您在上一篇文章中看到我的答案了吗?Swizzling是最后的解决方案,在这种情况下,所需要的只是使用日期格式化程序;但结果是一样的:(.ansi在控制台中也有“po日期”,但结果是一样的。是的,因为
NSLog
使用
description
方法。苹果以GMT(UTC)显示他们想要的日期。您不在GMT时区内。请使用您自己的日期格式化程序,查看答案的附加部分。先生,您太棒了。非常感谢。@S.J似乎是第二次使用的,@zaph先生,如果我试图在时间间隔内转换“日期”,我会得到相同的时区问题,我如何修复它?
NSString *dateString = @"01-10-2014 11:36 AM";
NSLog(@"dateString = %@", dateString);
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"dd-MM-yyyy hh:mm a"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [[NSDate alloc] init];

date = [dateFormatter dateFromString:dateString];
NSLog(@"dateFromString = %@", date);

NSString *displayDate = [dateFormatter stringFromDate:date];
NSLog(@"displayDate = %@", displayDate);