我正在为一个用 swift 编写的应用程序工作,我想操作日期和时间
I am working for an application written in swift and i want to manipulate dates and times
let timestamp = NSDateFormatter.localizedStringFromDate(
NSDate(),
dateStyle: .ShortStyle,
timeStyle: .ShortStyle
)
返回
2/12/15, 11:27 PM
如果我想要不同格式的日期和时间,例如欧洲格式的日期,如 dd/mm/yy
和没有 AM 和 PM 的 24 小时格式的小时.是否有一些我可以使用的功能,或者我必须使用 N 个字符串来重新排序各种元素?
if I want date and time in a different format, for example the date in a European format like dd/mm/yy
and the hours in the 24h format without AM and PM. Is there some function that i can use or i have to use N Strings to reorder the various elements?
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
}
为 Swift 4 编辑
Edit for Swift 4
func convertDateFormatter(date: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"//this your string date format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.locale = Locale(identifier: "your_loc_id")
let convertedDate = dateFormatter.date(from: date)
guard dateFormatter.date(from: date) != nil else {
assert(false, "no date from string")
return ""
}
dateFormatter.dateFormat = "yyyy MMM HH:mm EEEE"///this is what you want to convert format
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let timeStamp = dateFormatter.string(from: convertedDate!)
return timeStamp
}
这篇关于Swift - iOS - 不同格式的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!