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

查看:180
本文介绍了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,以及24h格式的小时(不带AM和PM).我可以使用某些函数还是必须使用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编辑

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天全站免登陆