Abh*_*bha 2 nsdateformatter ios ios7 ios8
我必须以不同的格式显示日期。
例如。7 月 21 日
我没有找到任何东西可以以这种格式转换我的日期。如果有人知道请帮助我。
Dar*_*ngs 10
迅速
extension Date {
func dateFormatWithSuffix() -> String {
return "dd'\(self.daySuffix())' MMMM yyyy"
}
func daySuffix() -> String {
let calendar = Calendar.current
let components = (calendar as NSCalendar).components(.day, from: self)
let dayOfMonth = components.day
switch dayOfMonth {
case 1, 21, 31:
return "st"
case 2, 22:
return "nd"
case 3, 23:
return "rd"
default:
return "th"
}
}
}
Run Code Online (Sandbox Code Playgroud)
例子
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = date.dateFormatWithSuffix()
print(dateFormatter.string(from: date))
// Output for current date: 22nd May 2019
Run Code Online (Sandbox Code Playgroud)
func setCurrentDate() {
let date = Date()
// Use this to add st, nd, th, to the day
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .ordinal
numberFormatter.locale = Locale.current
//Set other sections as preferred
let monthFormatter = DateFormatter()
monthFormatter.dateFormat = "MMM"
// Works well for adding suffix
let dayFormatter = DateFormatter()
dayFormatter.dateFormat = "dd"
let dayString = dayFormatter.string(from: date)
let monthString = monthFormatter.string(from: date)
// Add the suffix to the day
let dayNumber = NSNumber(value: Int(dayString)!)
let day = numberFormatter.string(from: dayNumber)!
yourDateLabel.text = "\(day) \(monthString)"
}
Run Code Online (Sandbox Code Playgroud)
标签目前将设置为5 月 25 日
Jul*_*era -3
您可以使用 NSDateFormatter 来显示您的 NSDate。它具有 dateStyle 和 timeStyle 等属性,可以轻松更改这些属性以获得您想要的格式。如果您需要更多灵活性,还可以使用 dateFormat 属性。
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.stringFromDate(NSDate())
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3679 次 |
| 最近记录: |