如何在Swift中以短格式获得当前日期?

时间:2022-09-18 07:28:59

In the images below you can see the code I wrote and the values of all the variables:

在下面的图片中,你可以看到我写的代码和所有变量的值:

class fun getCurrentShortDate() -> String {
    var todaysDate = NSDate()
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    var DateInFormat = dateFormatter.stringFromDate(todaysDate)

    return DateInFormat
}

Variable values

变量的值

As you can see the current date is found no problem, but when I try to change the NSDate to a string, it just won't do it.

正如您所看到的,当前日期没有发现任何问题,但是当我尝试将NSDate更改为字符串时,它不会这样做。

6 个解决方案

#1


27  

update: Xcode 8.2 • Swift 3.0.2

更新: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) }
}

Testing

测试

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, May 26, 2017 at 10:16:24 AM Brasilia Standard Time\n"
print(Date().shortDateTime)  // "5/26/17, 10:16 AM\n"

#2


7  

You can create a extension for easily transform a String into a NSDate.

您可以创建一个扩展,以便轻松地将字符串转换为NSDate。

extension NSDate {
    func dateFromString(date: String, format: String) -> NSDate {
        let formatter = NSDateFormatter()
        let locale = NSLocale(localeIdentifier: "en_US_POSIX")

        formatter.locale = locale
        formatter.dateFormat = format

        return formatter.dateFromString(date)!
    }
}

Than in your function you can NSDate().dateFromString("2015-02-04 23:29:28", format: "yyyy-MM-dd HH:mm:ss") and this should works. Input date don't need to be on the same format of output date.

在函数中可以使用NSDate()。dateFromString(“2015-02-04 23:29 28”,格式:“yyyyyy - mm -dd:mm:ss”),这个应该可以用。输入日期不需要与输出日期的格式相同。

func getCurrentShortDate() -> String {
    var todaysDate = NSDate().dateFromString("2015-02-04 23:29:28", format:  "yyyy-MM-dd HH:mm:ss")

    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    var DateInFormat = dateFormatter.stringFromDate(todaysDate)

    return DateInFormat
}

println(getCurrentShortDate())

The output is 04-02-2015.

输出是04-02-2015。

#3


7  

Update for Swift 3.0: Create an extension for Date

为Swift 3.0更新:为日期创建一个扩展

extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Usage:

用法:

Date().string(format: "yyyy-MM-dd")

Swift 2.2: Create an extension for NSDate

Swift 2.2:为NSDate创建扩展

extension NSDate {  
    func dateStringWithFormat(format: String) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.stringFromDate(self)
    }   
}

Usage:

用法:

NSDate().dateStringWithFormat("yyyy-MM-dd")

#4


0  

Swift 3

斯威夫特3

Using the extension created by @doovers and some format strings from this website, you get the following:

使用@doover创建的扩展名和本网站的一些格式字符串,您可以得到以下内容:

extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Usage:

用法:

Date().string(format: "EEEE, MMM d, yyyy") // Saturday, Oct 21, 2017
Date().string(format: "MM/dd/yyyy")        // 10/21/2017
Date().string(format: "MM-dd-yyyy HH:mm")  // 10-21-2017 03:31

Date().string(format: "MMM d, h:mm a")     // Oct 21, 3:31 AM
Date().string(format: "MMMM yyyy")         // October 2017
Date().string(format: "MMM d, yyyy")       // Oct 21, 2017

Date().string(format: "E, d MMM yyyy HH:mm:ss Z") // Sat, 21 Oct 2017 03:31:40 +0000
Date().string(format: "yyyy-MM-dd'T'HH:mm:ssZ")   // 2017-10-21T03:31:40+0000
Date().string(format: "dd.MM.yy")                 // 21.10.17

You could also pass milliseconds to date object like this:

您也可以将毫秒传递给日期对象,如下所示:

Date(1508577868947).string(format: "EEEE, MMM d, yyyy") // Saturday, Oct 21, 2017

#5


0  

Here's the way Apple suggests

这是苹果的建议

    let formatter = DateFormatter()
    formatter.locale = Locale.current
    formatter.dateStyle = .short
    let dateString = formatter.string(from: date)

or if the pre-defined format of .short, .medium, .long and .full are quite right create the template in a locale

或者,如果.short、.medium、.long和.full的预定义格式非常正确,那么在语言环境中创建模板

    let formatter = DateFormatter()
    formatter.locale = Locale.current
    formatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
    let dateString = formatter.string(from: date)

Here's the link

这是链接

#6


0  

let dateformatter1 = DateFormatter() dateformatter1.dateFormat = "ccc, d MMM yyy"

让dateformatter1 = DateFormatter() dateformatter1。日期格式= "ccc, d MMM yy"

    let dateString1 = dateformatter1.string(from: datePicker.date)
    print("Date Selected \(dateString1)")
    labelDate.text = dateString1

    let dateformatter2 = DateFormatter()
    dateformatter2.dateFormat = "dd-MM-yyyy"
    let dateString2 = dateformatter2.string(from: datePicker.date)
    print("Date Selected \(dateString2)")


    let dateformatter3 = DateFormatter()
    dateformatter3.dateFormat = "dd/MM/yyyy"
    let dateString3 = dateformatter3.string(from: datePicker.date)
    print("Date Selected \(dateString3)")

    let dateformatter4 = DateFormatter()
    dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
    let dateString4 = dateformatter4.string(from: datePicker.date)
    print("Date Selected \(dateString4)") 

I referred this article on Codzify.com. Really helpful.

我在Codzify.com上参考了这篇文章。真的有帮助。

#1


27  

update: Xcode 8.2 • Swift 3.0.2

更新: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) }
}

Testing

测试

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, May 26, 2017 at 10:16:24 AM Brasilia Standard Time\n"
print(Date().shortDateTime)  // "5/26/17, 10:16 AM\n"

#2


7  

You can create a extension for easily transform a String into a NSDate.

您可以创建一个扩展,以便轻松地将字符串转换为NSDate。

extension NSDate {
    func dateFromString(date: String, format: String) -> NSDate {
        let formatter = NSDateFormatter()
        let locale = NSLocale(localeIdentifier: "en_US_POSIX")

        formatter.locale = locale
        formatter.dateFormat = format

        return formatter.dateFromString(date)!
    }
}

Than in your function you can NSDate().dateFromString("2015-02-04 23:29:28", format: "yyyy-MM-dd HH:mm:ss") and this should works. Input date don't need to be on the same format of output date.

在函数中可以使用NSDate()。dateFromString(“2015-02-04 23:29 28”,格式:“yyyyyy - mm -dd:mm:ss”),这个应该可以用。输入日期不需要与输出日期的格式相同。

func getCurrentShortDate() -> String {
    var todaysDate = NSDate().dateFromString("2015-02-04 23:29:28", format:  "yyyy-MM-dd HH:mm:ss")

    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy"
    var DateInFormat = dateFormatter.stringFromDate(todaysDate)

    return DateInFormat
}

println(getCurrentShortDate())

The output is 04-02-2015.

输出是04-02-2015。

#3


7  

Update for Swift 3.0: Create an extension for Date

为Swift 3.0更新:为日期创建一个扩展

extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Usage:

用法:

Date().string(format: "yyyy-MM-dd")

Swift 2.2: Create an extension for NSDate

Swift 2.2:为NSDate创建扩展

extension NSDate {  
    func dateStringWithFormat(format: String) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.stringFromDate(self)
    }   
}

Usage:

用法:

NSDate().dateStringWithFormat("yyyy-MM-dd")

#4


0  

Swift 3

斯威夫特3

Using the extension created by @doovers and some format strings from this website, you get the following:

使用@doover创建的扩展名和本网站的一些格式字符串,您可以得到以下内容:

extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

Usage:

用法:

Date().string(format: "EEEE, MMM d, yyyy") // Saturday, Oct 21, 2017
Date().string(format: "MM/dd/yyyy")        // 10/21/2017
Date().string(format: "MM-dd-yyyy HH:mm")  // 10-21-2017 03:31

Date().string(format: "MMM d, h:mm a")     // Oct 21, 3:31 AM
Date().string(format: "MMMM yyyy")         // October 2017
Date().string(format: "MMM d, yyyy")       // Oct 21, 2017

Date().string(format: "E, d MMM yyyy HH:mm:ss Z") // Sat, 21 Oct 2017 03:31:40 +0000
Date().string(format: "yyyy-MM-dd'T'HH:mm:ssZ")   // 2017-10-21T03:31:40+0000
Date().string(format: "dd.MM.yy")                 // 21.10.17

You could also pass milliseconds to date object like this:

您也可以将毫秒传递给日期对象,如下所示:

Date(1508577868947).string(format: "EEEE, MMM d, yyyy") // Saturday, Oct 21, 2017

#5


0  

Here's the way Apple suggests

这是苹果的建议

    let formatter = DateFormatter()
    formatter.locale = Locale.current
    formatter.dateStyle = .short
    let dateString = formatter.string(from: date)

or if the pre-defined format of .short, .medium, .long and .full are quite right create the template in a locale

或者,如果.short、.medium、.long和.full的预定义格式非常正确,那么在语言环境中创建模板

    let formatter = DateFormatter()
    formatter.locale = Locale.current
    formatter.setLocalizedDateFormatFromTemplate("MM/dd/yyyy")
    let dateString = formatter.string(from: date)

Here's the link

这是链接

#6


0  

let dateformatter1 = DateFormatter() dateformatter1.dateFormat = "ccc, d MMM yyy"

让dateformatter1 = DateFormatter() dateformatter1。日期格式= "ccc, d MMM yy"

    let dateString1 = dateformatter1.string(from: datePicker.date)
    print("Date Selected \(dateString1)")
    labelDate.text = dateString1

    let dateformatter2 = DateFormatter()
    dateformatter2.dateFormat = "dd-MM-yyyy"
    let dateString2 = dateformatter2.string(from: datePicker.date)
    print("Date Selected \(dateString2)")


    let dateformatter3 = DateFormatter()
    dateformatter3.dateFormat = "dd/MM/yyyy"
    let dateString3 = dateformatter3.string(from: datePicker.date)
    print("Date Selected \(dateString3)")

    let dateformatter4 = DateFormatter()
    dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
    let dateString4 = dateformatter4.string(from: datePicker.date)
    print("Date Selected \(dateString4)") 

I referred this article on Codzify.com. Really helpful.

我在Codzify.com上参考了这篇文章。真的有帮助。