【发布时间】:2015-10-11 08:29:35
【问题描述】:
我必须以不同的格式显示日期。
例如。 7 月 21 日
我没有找到任何东西可以将我的日期转换成这种格式。如果有人知道,请帮助我。
【问题讨论】:
标签: ios ios7 ios8 nsdateformatter
我必须以不同的格式显示日期。
例如。 7 月 21 日
我没有找到任何东西可以将我的日期转换成这种格式。如果有人知道,请帮助我。
【问题讨论】:
标签: ios ios7 ios8 nsdateformatter
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)"
}
标签目前将设置为 5 月 25 日
【讨论】:
斯威夫特
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"
}
}
}
示例
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = date.dateFormatWithSuffix()
print(dateFormatter.string(from: date))
// Output for current date: 22nd May 2019
【讨论】:
NumberFormatter 与 .numberStyle = ordinal 一起使用,但某些语言也不希望在其日期中使用序数样式。
您可以使用 NSDateFormatter 来显示您的 NSDate。它具有诸如 dateStyle 和 timeStyle 之类的属性,可以轻松更改这些属性以获得所需的格式。如果您需要更大的灵活性,还有 dateFormat 属性。
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.stringFromDate(NSDate())
【讨论】: