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

时间:2015-02-04 22:41:08

标签: swift date nsdate nsdateformatter dateformatter

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

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

    return DateInFormat
}

Variable values

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

8 个答案:

答案 0 :(得分:33)

Xcode 8或更高版本•Swift 3或更高版本

extension Date {
    func localizedDescription(dateStyle: DateFormatter.Style = .medium,
                              timeStyle: DateFormatter.Style = .medium,
                           in timeZone : TimeZone = .current,
                              locale   : Locale = .current) -> String {
        Formatter.date.locale = locale
        Formatter.date.timeZone = timeZone
        Formatter.date.dateStyle = dateStyle
        Formatter.date.timeStyle = timeStyle
        return Formatter.date.string(from: self)
    }
    var localizedDescription: String { return localizedDescription() }
}

extension TimeZone {
    static let gmt = TimeZone(secondsFromGMT: 0)!
}
extension Formatter {
    static let date = DateFormatter()
}

Date().localizedDescription                                                // "Sep 26, 2018 at 12:03:41 PM"
Date().localizedDescription(in: .gmt)                                      // "Sep 26, 2018 at 3:03:41 PM" UTC TIME
Date().localizedDescription(dateStyle: .short, timeStyle: .short)          //  "9/26/18, 12:03 PM"
Date().localizedDescription(dateStyle: .full, timeStyle: .full)            //  "Wednesday, September 26, 2018 at 12:03:41 PM Brasilia Standard Time"
Date().localizedDescription(dateStyle: .full, timeStyle: .full, in: .gmt)  // "Wednesday, September 26, 2018 at 3:03:41 PM Greenwich Mean Time"

extension Date {
    var fullDate:  String { return localizedDescription(dateStyle: .full, timeStyle: .none)  }
    var shortDate: String { return localizedDescription(dateStyle: .short, timeStyle: .none)  }
    var fullTime:  String { return localizedDescription(dateStyle: .none, timeStyle: .full)  }
    var shortTime: String { return localizedDescription(dateStyle: .none, timeStyle: .short)   }
    var fullDateTime:  String { return localizedDescription(dateStyle: .full, timeStyle: .full)  }
    var shortDateTime: String { return localizedDescription(dateStyle: .short, timeStyle: .short)  }
}

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"

答案 1 :(得分:8)

您可以创建一个扩展程序,以便轻松地将String转换为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)!
    }
}

在你的功能中你可以NSDate().dateFromString("2015-02-04 23:29:28", format: "yyyy-MM-dd HH: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())

输出为04-02-2015

答案 2 :(得分:8)

Swift 3.0的更新:Date

创建扩展程序
extension Date {
    func string(format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: self)
    }
}

用法:

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

Swift 2.2:NSDate

创建扩展程序
extension NSDate {  
    func dateStringWithFormat(format: String) -> String {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.stringFromDate(self)
    }   
}

用法:

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

答案 3 :(得分:2)

Swift 3

使用@doovers创建的扩展程序和此website中的一些格式字符串,您将获得以下内容:

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

<强>用法:

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

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

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

答案 4 :(得分:2)

这是更改日期格式的最简单方法。

1.为日期扩展创建一个 swift 类。

extension Date {
    func today(format : String = "YYYY-MM-dd'T'HH:mm:ss.SSS") -> String {
        let date = Date()
        let formatter = DateFormatter()
        formatter.dateFormat = format
        return formatter.string(from: date)
    }
} 
  1. 如何使用扩展。

    let date = Date().today(format: "dd/MM/yy HH:mm:ss")

    打印(日期)

答案 5 :(得分:1)

这是Apple建议的方式

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

或者.short,.medium,.long和.full的预定义格式是否正确在区域设置中创建模板

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

这是link

答案 6 :(得分:0)

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

    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)") 

我在Codzify.com上提到了这篇文章。真有帮助。

答案 7 :(得分:0)

SWIFT 4或5

extension Date {

 static func getCurrentDate() -> String {

        let dateFormatter = DateFormatter()

        dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ss"

        return dateFormatter.string(from: Date())

    }
}

使用

print(Date.getCurrentDate())