如何转换,NSDate
以NSString
使得只有一年@"YYYY"格式输出到字符串?
怎么样...
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy"]; //Optionally for time zone conversions [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]]; NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance]; //unless ARC is active [formatter release];
Swift 4.2:
func stringFromDate(_ date: Date) -> String { let formatter = DateFormatter() formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy return formatter.string(from: date) }
我不知道我们都错过了这个:localizedStringFromDate:dateStyle:timeStyle:
NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterShortStyle timeStyle:NSDateFormatterFullStyle]; NSLog(@"%@",dateString);
输出'13/06/12 00:22:39 GMT + 03:00'
希望通过提供包括年,月,日在内的常规格式化程序来增加更多价值.您可以使用此格式化程序超过一年
[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"];
希望这有助于更多人
干杯Al
NSDate
网上有很多帮手,我倾向于使用:
https://github.com/billymeltdown/nsdate-helper/
自述文件摘要如下:
NSString *displayString = [NSDate stringForDisplayFromDate:date];
这会产生以下类型的输出:
‘3:42 AM’ – if the date is after midnight today ‘Tuesday’ – if the date is within the last seven days ‘Mar 1’ – if the date is within the current calendar year ‘Mar 1, 2008’ – else ;-)
在Swift中:
var formatter = NSDateFormatter() formatter.dateFormat = "yyyy" var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
NSDateFormatter *dateformate=[[NSDateFormatter alloc]init]; [dateformate setDateFormat:@"yyyy"]; // Date formater NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string NSLog(@"date :%@",date);