我想将NSString转换为NSdate并使用类别返回。我打电话遇到了麻烦。
+ (NSDate*)stringDateFromString:(NSString*)string
{
NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
return dateFromString;
}
+ (NSString*)StringFromDate :(NSDate*)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
return stringDate;
}
答案 0 :(得分:-1)
根据您提供的代码,您需要按如下方式创建一个类别: -
NSString + Utils.h
@interface NSString (Utils)
+ (NSDate*)dateFromString:(NSString*)string;
+ (NSString*)stringFromDate:(NSDate*)date;
@end
的NSString + Utils.m
@implementation NSString (Utils)
+ (NSDate*)dateFromString:(NSString*)string
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:string];
return dateFromString;
}
+ (NSString*)stringFromDate:(NSDate*)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:date];
NSLog(@"%@", stringDate);
return stringDate;
}
@end
并调用任一方法: -
NSDate *date = [NSString dateFromString:@"22-06-2015"];
NSString *string = [NSString stringFromDate:date];
NSLog(@"----------------");
NSLog(@"Date: %@", date);
NSLog(@"String: %@", string);
NSLog(@"----------------");
请注意allocating NSDateFormatter is expensive所以您可能不希望对这些方法进行太多调用(例如在表格视图中)。
XCTestCase的输出
Test Case '-[stackTests testExample]' started.
2015-06-23 07:12:59.601 xctest[3103:49715] 22-06-2015
2015-06-23 07:12:59.601 xctest[3103:49715] ----------------
2015-06-23 07:12:59.602 xctest[3103:49715] Date: 2015-06-21 23:00:00 +0000
2015-06-23 07:12:59.602 xctest[3103:49715] String: 22-06-2015
2015-06-23 07:12:59.602 xctest[3103:49715] ----------------
Test Case '-[stackTests testExample]' passed (0.002 seconds).