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

时间:2014-10-30 15:50:42

标签: ios objective-c nsdate nsdateformatter

- (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
}

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

  

string = 01-10-2014 11:36 AM

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

  

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

它出了什么问题?

1 个答案:

答案 0 :(得分:2)

问题是显示问题。

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

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

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

使用日期格式化程序以您想要的格式获取日期/时间。

示例代码:

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);

输出:

  

dateString = 01-10-2014 11:36 AM   dateFromString = 2014-10-01 15:36:00 +0000
  displayDate = 01-10-2014 11:36 AM

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

相关问题