在下面的图片中,您可以看到我写的代码和所有变量的值:
class fun getCurrentShortDate() -> String { var todaysDate = NSDate() var dateFormatter = NSDateFormatter() dateFormatter.dateFormate = "dd-MM-yyyy" var DateInFormat = dateFormatter.stringFromDate(todaysDate) return DateInFormat }
正如你可以看到当前日期被发现没有问题,但是当我尝试将NSDate更改为字符串时,它不会这样做.
更新:Xcode 8.2•Swift 3.0.2
extension DateFormatter { convenience init(dateStyle: Style) { self.init() self.dateStyle = dateStyle } convenience init(timeStyle: Style) { self.init() self.timeStyle = timeStyle } convenience init(dateStyle: Style,timeStyle: Style) { self.init() self.dateStyle = dateStyle self.timeStyle = timeStyle } }
extension Date { static let shortDate = DateFormatter(dateStyle: .short) static let fullDate = DateFormatter(dateStyle: .full) static let shortTime = DateFormatter(timeStyle: .short) static let fullTime = DateFormatter(timeStyle: .full) static let shortDateTime = DateFormatter(dateStyle: .short,timeStyle: .short) static let fullDateTime = DateFormatter(dateStyle: .full,timeStyle: .full) var fullDate: String { return Date.fullDate.string(from: self) } var shortDate: String { return Date.shortDate.string(from: self) } var fullTime: String { return Date.fullTime.string(from: self) } var shortTime: String { return Date.shortTime.string(from: self) } var fullDateTime: String { return Date.fullDateTime.string(from: self) } var shortDateTime: String { return Date.shortDateTime.string(from: self) } }
测试
print(Date().fullDate) // "Friday,May 26,2017\n" print(Date().shortDate) // "5/26/17\n" print(Date().fullTime) // "10:16:24 AM Brasilia Standard Time\n" print(Date().shortTime) // "10:16 AM\n" print(Date().fullDateTime) // "Friday,2017 at 10:16:24 AM Brasilia Standard Time\n" print(Date().shortDateTime) // "5/26/17,10:16 AM\n"