Convert string to date with timezone

2019-09-15 05:26发布

问题:

i have date string 2017-01-03T10:45:00.000+02:00 and I need to transfer it to something like this 2017-01-03 10:45:00 +0200

 let formatter = DateFormatter()
 formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
 // this formatter returning 2017-01-03 08:45:00 +0000 but I need 
 // 2017-01-03 10:45:00 +0200

Thank you for your help!

回答1:

Try this,

Swift 3.0

let dateStr = "2017-01-03T10:45:00.000+02:00"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'.000\'z"
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: dateStr)

print("Date from String : \(date)")

dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx'"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 7200) as TimeZone!

print("String From Date : \(dateFormatter.string(from: date!))")

Result:

Date from String : Optional(2017-01-03 08:45:00 +0000)

String From Date : 2017-01-03 10:45:00 +0200



回答2:

This one works for me, Hope it help's you

 let dateString = "2017-01-03 08:45:00 +0000"

// create dateFormatter with UTC time format
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx"
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
let date = dateFormatter.date(from: dateString)// create   date from string
print("Date1 : \(date)")
// change to a readable time format and change to local time zone
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss xxxx'"
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 7200) as TimeZone!
print("Date2 : \(dateFormatter.string(from: date!))")   


回答3:

If you want to convert String to Date try the below code and let me know,

let dateString = "2016-10-25"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let FormatDate = dateFormatter.dateFromString(dateString)
print(FormatDate)

More over you can get the time from below format:

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"


回答4:

Try this:

let dateString = "2017-01-03T10:45:00.000+02:00"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss SSSZ"
let FormatDate = dateFormatter.dateFromString(dateString)
print(FormatDate)