如何仅将日期从 ISO8601 时间戳获取为字符串 ios?

How to get only date from ISO8601 timestamp to as string ios?

您好,我有 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.

格式获取日期

使用 NSRange 找到解决方案:

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

请尝试此代码。

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