Swift
Easier way to get any elements of date as an optional String.
extension Date {
// Year
var currentYear: String? {
return getDateComponent(dateFormat: "yy")
//return getDateComponent(dateFormat: "yyyy")
}
// Month
var currentMonth: String? {
return getDateComponent(dateFormat: "M")
//return getDateComponent(dateFormat: "MM")
//return getDateComponent(dateFormat: "MMM")
//return getDateComponent(dateFormat: "MMMM")
}
// Day
var currentDay: String? {
return getDateComponent(dateFormat: "dd")
//return getDateComponent(dateFormat: "d")
}
func getDateComponent(dateFormat: String) -> String? {
let format = DateFormatter()
format.dateFormat = dateFormat
return format.string(from: self)
}
}
let today = Date()
print("Current Year - \(today.currentYear)") // result Current Year - Optional("2017")
print("Current Month - \(today.currentMonth)") // result Current Month - Optional("7")
print("Current Day - \(today.currentDay)") // result Current Day - Optional("10")