如何将字符串转换为日期?

时间:2013-08-26 07:13:55

标签: ios objective-c nsstring nsdate nsdateformatter

我知道这里有很多关于这个主题的问题。但是,我似乎无法解决我的问题。

我有这个字符串,例如,“2013-08-26 12:11:51 10:17:25”,我只想抓住“2013-08-26”,然后将其转换回字符串。我尝试了许多方法但没有成功:

NSMutableString *visitDate = [[NSMutableString alloc] initWithString:@"2013-08-26 10:17:25"];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormat dateFromString:visitDate];
NSLog(@"date: %@", date);
NSMutableString *returnConvertedDateString = [[NSMutableString alloc]initWithString:(NSMutableString *)date];    
NSLog(@"converted string: %@", returnConvertedDateString);

上面的NSLog语句的结果是:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSPlaceholderMutableString initWithString:]: nil argument'

我也尝试过:

-  (NSMutableString *) convertDateToString : (NSMutableString *)visitDate{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:(NSDate *)visitDate];
NSMutableString *returnConvertedDateString = [[NSMutableString alloc]initWithFormat:@"%ld-%ld-%ld", (long)[components year], (long)[components month],(long)[components day]];
return returnConvertedDateString;
}

4 个答案:

答案 0 :(得分:1)

您的字符串中有重复的时间。假设这是一个错字,你可以得到你想要的东西。

NSDateFormatter * dateFormatter = [NSDateFormatter new];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate * date = [dateFormatter dateFromString:@"2013-08-26 12:11:51"];

[dateFormatter setDateFormat:@"yyyy-MM-dd"];

NSString * dateString = [dateFormatter stringFromDate:date];

NSLog(@"%@", dateString);

答案 1 :(得分:0)

假设日期时间字符串的格式为NSString *visitDate = @"2013-08-26 12:11:51 10:17:25";

试试这个方法:

-  (NSString *) convertDateToString:(NSString *)visitDate{
  NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\d{4}-\d{2}-\d{2})" options:NSRegularExpressionCaseInsensitive error:NULL];
  NSTextCheckingResult *firstMatch = [regex firstMatchInString:opening_time options:0 range:NSMakeRange(0, [visitDate length])];
  if (firstMatch) {
      NSRange range = [firstMatch rangeAtIndex:0];
      NSString *dateString = [urlString substringWithRange:range];
      return dateString;
  }
  return nil;
}

此方法应仅提取字符串的yyyy-MM-dd部分,并以字符串表示形式返回。如果需要,请记住将其修改为可变版本。

答案 2 :(得分:0)

最简单的方法是

NSMutableString * visitDate = [[NSMutableString alloc] initWithString:@“2013-08-26 12:11:51”];

    NSArray *items = [visitDate componentsSeparatedByString:@" "];
    NSLog(@"%@",[items objectAtIndex:0]);

答案 3 :(得分:0)

如果你想要一个字符串,为什么不只返回前10个字符?

[dateString substringToIndex:10];