问题描述
- 如何格式化字符串变量的数据?
-
在NSString
存日期:1900-01-01T11:00:00
需要进行格式化,然后加了一个格式器:
NSDateFormatter *df = [[NSDateFormatter alloc] init]; [df setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
如何进行格式化?
NSString* formatedDateString = [df ???];
解决方案
你要创建两个日期格式器。一个用于解析,一个用于格式化~
NSString * targetString = @"1900-01-01'T'11:00:00";
NSDateFormatter *parseFormat = [[NSDateFormatter alloc] init];
[parseFormat setDateFormat:@"yyyy-MM-ddThh:mm:ss"];
NSDate * date = [parseFormat dateFromString:targetString];
NSDateFormatter * outputFormat = [[NSDateFormatter alloc] init];
[outputFormat setDateFormat:@"dd/MM/yyyy hh:mm:ss a";
NSString * outputString = [parseFormat stringFromDate:date];
解决方案二:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: %@", formattedDateString);
// Output for locale en_US: "formattedDateString: Jan 2, 2001".
解决方案三:
NSString * targetString = @"1900-01-01'T'11:00:00";
NSDateFormatter *parseFormat = [[NSDateFormatter alloc] init];
[parseFormat setDateFormat:@"yyyy-MM-ddThh:mm:ss"];
NSDate * date = [parseFormat dateFromString:targetString];
NSDateFormatter * outputFormat = [[NSDateFormatter alloc] init];
[outputFormat setDateFormat:@"dd/MM/yyyy hh:mm:ss a";
NSString * outputString = [parseFormat stringFromDate:date];