objective-c 将 NSDate 转换为 NSString

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/576265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:10:51  来源:igfitidea点击:

Convert NSDate to NSString

objective-cswiftnsstringnsdate

提问by 4thSpace

How do I convert, NSDateto NSStringso that only the year in @"yyyy"format is output to the string?

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

回答by Allan

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 :

斯威夫特 4.2:

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

回答by Oded Ben Dov

I don't know how we all missed this: localizedStringFromDate:dateStyle:timeStyle:

我不知道我们怎么都错过了这个:localizedStringFromDate:dateStyle:timeStyle:

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] 
                                                      dateStyle:NSDateFormatterShortStyle 
                                                      timeStyle:NSDateFormatterFullStyle];
NSLog(@"%@",dateString);

outputs '13/06/12 00:22:39 GMT+03:00'

输出 '13/06/12 00:22:39 GMT+03:00'

回答by Al Pascual

Hope to add more value by providing the normal formatter including the year, month and day with the time. You can use this formatter for more than just a year

希望通过提供包括年、月和日在内的普通格式化程序来增加更多的价值。您可以使用此格式化程序超过一年

[dateFormat setDateFormat: @"yyyy-MM-dd HH:mm:ss zzz"]; 

回答by Nik Burns

there are a number of NSDatehelpers on the web, I tend to use:

NSDate网上有很多助手,我倾向于使用:

https://github.com/billymeltdown/nsdate-helper/

https://github.com/billymeltdown/nsdate-helper/

Readme extract below:

自述文件摘录如下:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

This produces the following kinds of output:

这会产生以下类型的输出:

‘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 ;-)

回答by Dave Patrick

In Swift:

在斯威夫特:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)

回答by S R Nayak

  NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
  [dateformate setDateFormat:@"yyyy"]; // Date formater
  NSString *date = [dateformate stringFromDate:[NSDate date]]; // Convert date to string
  NSLog(@"date :%@",date);

回答by Gank

+(NSString*)date2str:(NSDate*)myNSDateInstance onlyDate:(BOOL)onlyDate{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (onlyDate) {
        [formatter setDateFormat:@"yyyy-MM-dd"];
    }else{
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }

    //Optionally for time zone conversions
    //   [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"..."]];

    NSString *stringFromDate = [formatter stringFromDate:myNSDateInstance];
    return stringFromDate;
}

+(NSDate*)str2date:(NSString*)dateStr{
    if ([dateStr isKindOfClass:[NSDate class]]) {
        return (NSDate*)dateStr;
    }

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];
    return date;
}

回答by pix0r

If you don't have NSDate-descriptionWithCalendarFormat:timeZone:locale:available (I don't believe iPhone/Cocoa Touch includes this) you may need to use strftime and monkey around with some C-style strings. You can get the UNIX timestamp from an NSDateusing NSDate -timeIntervalSince1970.

如果你没有NSDate-descriptionWithCalendarFormat:timeZone:locale:可用的(我不相信 iPhone/Cocoa Touch 包括这个),你可能需要使用 strftime 和猴子来处理一些 C 风格的字符串。您可以从NSDateusing 中获取 UNIX 时间戳NSDate -timeIntervalSince1970

回答by Nazariy Vlizlo

Just add this extension:

只需添加此扩展名:

extension NSDate {
    var stringValue: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yourDateFormat"
        return formatter.stringFromDate(self)
    }
}

回答by neoneye

If you are on Mac OS X you can write:

如果您使用的是 Mac OS X,您可以编写:

NSString* s = [[NSDate date] descriptionWithCalendarFormat:@"%Y_%m_%d_%H_%M_%S" timeZone:nil locale:nil];

However this is not available on iOS.

但是,这在 iOS 上不可用。