小编典典

将NSDate转换为NSString

swift

如何转换,NSDateNSString使得只有一年 @“YYYY” 格式输出到字符串?


阅读 269

收藏
2020-07-07

共1个答案

小编典典

怎么样…

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)
}
2020-07-07