Swift – iOS – 不同格式的date和时间

我正在为swift写一个应用程序,我想操纵date和时间

let timestamp = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .ShortStyle, timeStyle: .ShortStyle) 

回报

 2/12/15, 11:27 PM 

如果我需要不同的格式的date和时间,例如欧洲格式的date,如dd / mm / yy和24小时的格式没有上午和下午的时间有一些function,我可以使用或我必须使用Nstring重新排列各种元素?

 func convertDateFormater(date: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" dateFormatter.timeZone = NSTimeZone(name: "UTC") guard let date = dateFormatter.dateFromString(date) else { assert(false, "no date from string") return "" } dateFormatter.dateFormat = "yyyy MMM EEEE HH:mm" dateFormatter.timeZone = NSTimeZone(name: "UTC") let timeStamp = dateFormatter.stringFromDate(date) return timeStamp } 

如前所述,您必须使用NSDateFormatter来格式化您的NSDate对象。 最简单的方法是创build一个只读的计算属性NSDate扩展。

只读计算属性

具有getter但没有setter的计算属性被称为只读计算属性。 只读计算属性总是返回一个值,可以通过点语法访问,但不能设置为不同的值。

注意

您必须将计算属性(包括只读计算属性)用var关键字声明为variables属性,因为它们的值不是固定的。 let关键字仅用于常量属性,表示一旦将它们设置为实例初始化的一部分,就不能更改它们的值。

您可以通过删除get关键字及其大括号来简化只读计算属性的声明:

 extension NSDateFormatter { convenience init(dateFormat: String) { self.init() self.dateFormat = dateFormat } } extension NSDate { struct Formatter { static let custom = NSDateFormatter(dateFormat: "dd/M/yyyy, H:mm") } var customFormatted: String { return Formatter.custom.stringFromDate(self) } } 

要将其转换回来,您可以创build另一个只读的计算属性,但作为string扩展名:

 extension String { var asDate: NSDate? { return NSDate.Formatter.custom.dateFromString(self) } func asDateFormatted(with dateFormat: String) -> NSDate? { return NSDateFormatter(dateFormat: dateFormat).dateFromString(self) } } 

用法:

 let stringFromDate = NSDate().customFormatted // "14/7/2016, 2:00" if let date = stringFromDate.asDate { // "Jul 14, 2016, 2:00 AM" print(date) // "2016-07-14 05:00:00 +0000\n" date.customFormatted // "14/7/2016, 2:00" } "14/7/2016".asDateFormatted(with: "dd/MM/yyyy") // "Jul 14, 2016, 12:00 AM" 

正如Zaph所说,你需要遵循文档。 诚然,与其他类别的参考相比,这可能不是最直接的。 简短的答案是,您使用date字段符号表来找出你想要的格式。 一旦你做到了:

 let dateFormatter = NSDateFormatter() //the "M/d/yy, H:mm" is put together from the Symbol Table dateFormatter.dateFormat = "M/d/yy, H:mm" dateFormatter.stringFromDate(NSDate()) 

如果需要将string的date转换为NSDate,则还需要能够使用该表。

 let dateAsString = "02/12/15, 16:48" let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "M/d/yyyy, H:mm" let date = dateFormatter.dateFromString(dateAsString) 

当前date到格式string的时间:

 let currentDate = Date() let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy hh:mm:ss a" let convertedDate: String = dateFormatter.string(from: currentDate) //08/10/2016 01:42:22 AM 

更多date时间格式

如果你想使用面向协议的编程(Swift 3)

1)创build一个Dateable协议

 protocol Dateable { func userFriendlyFullDate() -> String func userFriendlyHours() -> String } 

2)扩展Date类并实现Dateable协议

 extension Date: Dateable { var formatter: DateFormatter { return DateFormatter() } /** Return a user friendly hour */ func userFriendlyFullDate() -> String { // Customize a date formatter formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" formatter.timeZone = TimeZone(abbreviation: "UTC") return formatter.string(from: self) } /** Return a user friendly hour */ func userFriendlyHours() -> String { // Customize a date formatter formatter.dateFormat = "HH:mm" formatter.timeZone = TimeZone(abbreviation: "UTC") return formatter.string(from: self) } // You can add many cases you need like string to date formatter } 

3)使用它

 let currentDate: Date = Date() let stringDate: String = currentDate.userFriendlyHours() // Print 15:16 

我使用@ iod07类似的方法,但作为扩展。 另外,我在评论中添加了一些解释,以了解它是如何工作的。

基本上,只需将其添加到视图控制器的顶部或底部即可。

 extension NSString { class func convertFormatOfDate(date: String, originalFormat: String, destinationFormat: String) -> String! { // Orginal format : let dateOriginalFormat = NSDateFormatter() dateOriginalFormat.dateFormat = originalFormat // in the example it'll take "yy MM dd" (from our call) // Destination format : let dateDestinationFormat = NSDateFormatter() dateDestinationFormat.dateFormat = destinationFormat // in the example it'll take "EEEE dd MMMM yyyy" (from our call) // Convert current String Date to NSDate let dateFromString = dateOriginalFormat.dateFromString(date) // Convert new NSDate created above to String with the good format let dateFormated = dateDestinationFormat.stringFromDate(dateFromString!) return dateFormated } } 

假设您要将"16 05 05"转换为"Thursday 05 May 2016"并且您的date声明如下: let date = "16 06 05"

然后只需拨打以下电话:

 let newDate = NSString.convertFormatOfDate(date, originalFormat: "yy MM dd", destinationFormat: "EEEE dd MMMM yyyy") 

希望能帮助到你 !

你已经find了NSDateFormatter ,只是阅读它的文档。

NSDateFormatter类参考

用于格式字符定义
请参阅: ICU格式化date和时间
另外: date字段SymbolTable。 。

Swift 3:

 //This gives month as three letters (Jun, Dec, etc) let justMonth = DateFormatter() justMonth.dateFormat = "MMM" myFirstLabel.text = justMonth.string(from: myDate) //This gives the day of month, with no preceding 0s (6,14,29) let justDay = DateFormatter() justDay.dateFormat = "d" mySecondLabel.text = justDay.string(from: myDate) //This gives year as two digits, preceded by an apostrophe ('09, '16, etc) let justYear = DateFormatter() justYear.dateFormat = "yy" myThirdLabel.text = "'\(justYear.string(from: lastCompDate))" 

有关更多格式,请查看带有所有可用格式的codingExplorer表的链接 。 每个date组件都有几个选项,例如:

年:

  • “y” – 2016(像1年的早期date将是:“1”)
  • “yy” – 16(第1年:“01”
  • “yyy” – 2016(1年:“001”)
  • “yyyy” – 2016(第1年:“0001”)

几乎每个组件都有2-4个选项,用第一个字母表示格式(date是“d”,小时是“h”等)。 然而,月份是大写字母“M”,因为小写字母“m”是为分钟保留的。 还有一些例外,所以检查链接!

 let usDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-US")) //usDateFormat now contains an optional string "MM/dd/yyyy" let gbDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "en-GB")) //gbDateFormat now contains an optional string "dd/MM/yyyy" let geDateFormat = DateFormatter.dateFormat(FromTemplate: "MMddyyyy", options: 0, locale: Locale(identifier: "de-DE")) //geDateFormat now contains an optional string "dd.MM.yyyy" 

您可以按以下方式使用它从设备获取当前格式:

 let currentDateFormat = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: Locale.current)