仅将日期转换为时间

时间:2016-12-22 12:42:22

标签: ios swift3 nsdate nsdateformatter

我有这样的日期字符串: - 2016-12-20T15:26:21+11:00

需要什么样的DateFormatter(或其他),以便我可以在设备的当前时区获得时间。

3 个答案:

答案 0 :(得分:2)

输入为ISO8601,合适的解决方案为DateFormatter。如果没有localetimeZone的特定设置,格式化程序会考虑当前的区域设置和时区。

let dateString = "2016-12-20T15:26:21+11:00"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
formatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
let date = formatter.date(from:dateString)
formatter.timeStyle = .medium
formatter.dateStyle = .none
print(formatter.string(from: date!))

答案 1 :(得分:0)

您可以使用以下代码将日期字符串转换为仅时间

       let sourceDateString = "2016-12-20T15:26:21+11:00"
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        formatter.locale = Locale(identifier: "en-US")
        formatter.timeZone = TimeZone(identifier: "UTC")
        let date = formatter.date(from: sourceDateString)
        print("\(date)")

        formatter.timeZone = NSTimeZone.local
        formatter.dateFormat = "HH:mm:ss"

        let strDate = formatter.string(from: date!)
        print(strDate)

答案 2 :(得分:0)

这是一种现代化的方式。你可以在操场上试试:

let dateString = "2016-12-20T15:26:21+11:00"

// First use an ISO8601 Date formatter to turn the string into a date.

let inputFormatter = ISO8601DateFormatter()
let date = inputFormatter.date(from: dateString)! // Force unwrapping as this is a demo - you should be more careful.

// Now use a normal DateFormatter set to your current locale, turn of the date display, and use a short Time display style:

let outputFormatter = DateFormatter()
outputFormatter.locale = Locale.current
outputFormatter.dateStyle = .none
outputFormatter.timeStyle = .short

let display = outputFormatter.string(from: date)

// As I'm in the UK and the simulator local is US, I get "4:26 AM"
// Your result will be different.