Convert NSDate to NSString

4thSpace picture 4thSpace · Feb 23, 2009 · Viewed 320.7k times · Source

How do I convert, NSDate to NSString so that only the year in @"yyyy" format is output to the string?

Answer

Allan picture Allan · May 31, 2009

How about...

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