Swift - iOS - 不同格式的日期和时间 [英] Swift - iOS - Dates and times in different format

查看:28
本文介绍了Swift - iOS - 不同格式的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一个用 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 - 不同格式的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆