我的NSString是这段代码中的日期和时间:“YYYY-MM-DD HH:mm:SS”我希望它像德国风格一样:“DD.MM.YYY HH:mm:DD “
如何解决?
答案 0 :(得分:15)
将一个日期字符串转换为另一种格式的示例:
NSString * currentDateString = @“04-08-2012 08:16:00”;
NSLog(@"currentDateString: %@", currentDateString);
NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
[dateFormater setDateFormat:@"MM-DD-yyyy HH:mm:ss"];
NSDate *currentDate = [dateFormater dateFromString:currentDateString];
NSLog(@"currentDate: %@", currentDate);
[dateFormater setDateFormat:@"yyyy-MM-DD HH:mm:ss"];
NSString *convertedDateString = [dateFormater stringFromDate:currentDate];
NSLog(@"convertedDateString: %@", convertedDateString);
[dateFormater setDateFormat:@"DD.MM.yyy HH:mm:DD"];
NSString *germanDateString = [dateFormater stringFromDate:currentDate];
NSLog(@"germanDateString: %@", germanDateString);
NSLog输出:
currentDateString:04-08-2012 08:16:00
currentDate:2012-04-01 12:16:00 +0000
convertedDateString:2012-04-92 08:16:00
germanDateString:92.04.2012 08:16:92
答案 1 :(得分:3)
NSString* input = @"2012-04-08 13:05:49";
NSString* year = [input substringWithRange: NSMakeRange( 0, 4)];
NSString* month = [input substringWithRange: NSMakeRange( 5, 2)];
NSString* day = [input substringWithRange: NSMakeRange( 8, 2)];
NSString* time = [input substringWithRange: NSMakeRange(11, 8)];
NSString* output = [NSString stringWithFormat:@"%@.%@.%@ %@",day,month,year,time];
答案 2 :(得分:1)
使用NSDateFormatter将其转换为NSDate对象,然后使用formatter导出字符串。按照有关dateFromString&的文档进行操作。 stringFromDate。