我如何转换,NSDate到NSString,以便只有年在@“yyyy”格式输出到字符串?


当前回答

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:@"%ld", year];

其他回答

迅速:

var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy"
var dateString = formatter.stringFromDate(YourNSDateInstanceHERE)
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:myNSDateInstance];
NSInteger year = [components year];
// NSInteger month = [components month];
NSString *yearStr = [NSString stringWithFormat:@"%ld", year];

如果你在Mac OS X上,你可以这样写:

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

但是这在iOS上是不可用的。

迅速回答

static let dateformat: String = "yyyy-MM-dd'T'HH:mm:ss"
public static func stringTodate(strDate : String) -> Date
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    let date = dateFormatter.date(from: strDate)
    return date!
}
public static func dateToString(inputdate : Date) -> String
{

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = dateformat
    return formatter.string(from: inputdate)

}

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

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

自述摘录如下:

  NSString *displayString = [NSDate stringForDisplayFromDate:date];

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

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