4

我有一个 NSString,它是这段代码中的日期和时间:“YYYY-MM-DD HH:mm:SS”,我想像德国风格一样使用它:“DD.MM.YYY HH:mm:DD”

怎么解决?

4

3 回答 3

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 convertDateString
:2012-04-92 08:16:00
GermanDateString:92.04.2012 08:16: 92

于 2012-04-08T12:24:07.823 回答
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];
于 2012-04-08T11:14:06.900 回答
1

使用 NSDateFormatter 将其转换为 NSDate 对象,然后使用格式化程序导出字符串。遵循有关 dateFromString 和 stringFromDate 的文档。

于 2012-04-08T12:08:02.037 回答