swift – NSDateFormatter.stringFromDate(NSDate())返回空字符串

在下面的图片中,您可以看到我写的代码和所有变量的值:
class fun getCurrentShortDate() -> String {
    var todaysDate = NSDate()
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormate = "dd-MM-yyyy"
    var DateInFormat = dateFormatter.stringFromDate(todaysDate)

    return DateInFormat
}

Variable values

正如你可以看到当前日期被发现没有问题,但是当我尝试将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"

相关文章

Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章。自从苹果发布 Swfit 编程语言,就成为了...
快,快,快!动动您的小手,分享给更多朋友! 苹果去年推出了全新的编程语言Swift,试图让iOS开发更简单...
开发者(KaiFaX) 面向开发者、程序员的专业平台! 和今年年初承诺的一样,苹果贴出了Swift语言的源码,...
本文由@Chun发表于Chun Tips :http://chun.tips/blog/2014/12/11/shi-yong-swift-gou-jian-zi-ding-yi...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...
本文由CocoaChina译者leon(社区ID)翻译 原文:THE RIGHT WAY TO WRITE A SINGLETON 在之前的帖子里聊过...