How do I get the current Date in short format in Swift

前端 未结 7 876
北荒
北荒 2020-11-22 15:10

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

class fun getCurrentShortDate() -> String {
    var todaysDate = NSD         


        
7条回答
  •  Happy的楠姐
    2020-11-22 15:52

    You can create a extension for easily transform a String into a 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.

    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.

提交回复
热议问题