Swift转换日历组件?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (56)

我想以这种格式显示日历

提问于
用户回答回答于

NSDateFormattermonthSymbols

所以试试这个:

let dateFormatter: NSDateFormatter = NSDateFormatter()

let months = dateFormatter.shortMonthSymbols
let monthSymbol = months[month-1] as! String // month - from your date components

println(monthSymbol)
用户回答回答于

您可以如下所示使用DateFor:

extension Formatter {
    static let monthMedium: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "LLL"
        return formatter
    }()
    static let hour12: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "h"
        return formatter
    }()
    static let minute0x: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "mm"
        return formatter
    }()
    static let amPM: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "a"
        return formatter
    }()
}
extension Date {
    var monthMedium: String  { return Formatter.monthMedium.string(from: self) }
    var hour12:  String      { return Formatter.hour12.string(from: self) }
    var minute0x: String     { return Formatter.minute0x.string(from: self) }
    var amPM: String         { return Formatter.amPM.string(from: self) }
}

let date = Date()

let dateMonth  = date.monthMedium  // "May"
let dateHour   = date.hour12       // "1"
let dateMinute = date.minute0x     // "18"
let dateAmPm = date.amPM           // "PM"

扫码关注云+社区

领取腾讯云代金券