在ios中将字符串转换为日期

时间:2014-06-24 09:14:02

标签: ios nsdate nsdateformatter

我的数据采用JSON格式,其中包含一些日期:

"NOME_PUBBL_LINEA" = "FOLLONICA - PIOMBINO";
    "ORA_ARRIVA" = "1899-12-30T06:45:00";
    "ORA_PARTE" = "1899-12-30T05:50:00";

我想将其转换为:

 ora_arriva = 6.45,
   ora_parte = 5.50

我试过以下:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'+02:00'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Italy/Rome"]];
NSDate *dte = [dateFormat dateFromString:dataDic[@"ORA_ARRIVA"]];

但它给了我像

  

1899-12-30 00:51:40 +0000

for ora_arriva。

3 个答案:

答案 0 :(得分:0)

[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'+02:00'"];

只是yyyy:)

答案 1 :(得分:0)

dateFromString返回一个NSDate。您需要获取该NSDate对象并构建您的时间:

NSDate *myDate = [NSDate date];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comp = [gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:myDate];

NSLog(@"current time = %ld:%ld", [comp hour], [comp minute]);

myDate替换为您从dateFormatter

返回的实际NSDate

答案 2 :(得分:0)

你需要这样的东西

[dateformatter setDateFormat:@"MM-dd-yyyy hh:mm:ss"];
NSString *dateString = [dateformatter stringFromDate:adate];