小编典典

将 NSDate 转换为 NSString

all

如何转换,NSDate以便NSString仅将 @”yyyy” 格式的年份输出到字符串?


阅读 43

收藏
2022-05-18

共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];

斯威夫特 4.2:

func stringFromDate(_ date: Date) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "dd MMM yyyy HH:mm" //yyyy
    return formatter.string(from: date)
}
2022-05-18