如何只将ISO8601时间戳的日期作为字符串ios?

时间:2016-01-13 06:03:37

标签: objective-c datetime nsdate nsdateformatter ios9.1

嗨我在ISO8601中有日期格式作为示例:

NSString *currentDateString = @"2016-01-12T21:21:22.737+05:30";

我想从此字符串中仅获取 2016-01-12 的日期:

我试过

[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
NSLog(@"CurrentDate:%@", currentDate);

它重新调整为null但我希望以 yyyy-MM-dd 的格式获取日期。

2 个答案:

答案 0 :(得分:0)

请尝试此代码。

NSString *dateString = @"2013-04-18T08:49:58.157+0000";
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
// Always use this locale when parsing fixed format date strings
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:posix];
NSDate *date = [formatter dateFromString:dateString];
NSLog(@"date = %@", date);

答案 1 :(得分:-1)

使用 NSRange 找到解决方案:

NSString *currentDateString = @"2016-01-12T21:21:22.737+05:30";
NSRange range = [currentDateString rangeOfString:@"T"];
NSString *newString = [currentDateString substringToIndex:range.location];
NSLog(@"%@",newString);