2

i am using following code to convert string to Date

    let strTime = "2015-07-27 19:29"
    let formatter = DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm"
    var date = formatter.date(from: strTime)

but its output as follows

we can see time in the Date is not correct (13:59)as we given on string (19:29)

Ankit Kushwah
  • 539
  • 4
  • 16
  • 1
    Where you you live? In which Timezone? For instance, in France with your current code, I get "2015-07-27 17:29:00 +0000". But that's because we are in summer and there is 2 hours difference with UTC. – Larme Jun 07 '18 at 13:10
  • It seems to be an issue related to the time zone... – Ahmad F Jun 07 '18 at 13:13

1 Answers1

0

Add TimeZone to your formatter :

let strTime          = "2015-07-27 19:29"
let formatter        = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm"
formatter.timeZone   = TimeZone(abbreviation: "UTC") // Whatever your timeZone is
var date             = formatter.date(from: strTime)
print(date)
Sharad Chauhan
  • 4,821
  • 2
  • 25
  • 50
  • Only do this if you want to treat `strTime` as being in the UTC timezone. That may or may not be appropriate. – rmaddy Jun 07 '18 at 14:45