Convert string to date with timezone

2019-09-15 04:54发布

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!

4条回答
SAY GOODBYE
2楼-- · 2019-09-15 05:28

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"
查看更多
疯言疯语
3楼-- · 2019-09-15 05:42

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)
查看更多
老娘就宠你
4楼-- · 2019-09-15 05:47

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

查看更多
冷血范
5楼-- · 2019-09-15 05:49

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!))")   
查看更多
登录 后发表回答