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


当前回答

网络上有很多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 ;-)

其他回答

swift格式:

func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {

    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: calndarIdentifier)
    formatter.dateFormat = dateFormat

    return formatter
}


//Usage
let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018

iOS 15更新

iOS 15现在支持直接在Date对象上调用.格式化,而不需要显式的DateFormatter。

常见格式示例

文档

date.formatted() // 6/8/2021, 7:30 PM
date.formatted(date: .omitted, time: .complete) // 19:30
date.formatted(date: .omitted, time: .standard) // 07:30 PM
date.formatted(date: .omitted, time: .shortened) // 7:30 PM
date.formatted(date: .omitted, time: .omitted)

替代语法

文档

// We can also specify each DateComponent separately by chaining modifiers.
date.formatted(.dateTime.weekday(.wide).day().month().hour().minute())
// Tuesday, Jun 8, 7:30 pm

// Answer to specific question
date.formatted(.dateTime.year())

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

objective - c:

NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = @"yyyy";
NSString *dateString = [formatter stringFromDate:date];

迅速:

let now = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let dateString = formatter.string(from: now) 

这是nsdateformatter的一个好网站。您可以在不同的本地使用不同的DateFormatter预览日期字符串。

迅速回答

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)

}