如何将 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)
}

关于objective-c - 将 NSDate 转换为 NSString,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/576265/

10-13 04:00