2

Hi I want to get time as 11:40 from "2017-07-31T11:40:00.000Z"

Below is the code I am using:

     let formatter = Foundation.DateFormatter()
        formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
        let date1  = formatter.date(from: data.arvTime)
        print("date:\(String(describing: date1))")
        let dateFormatterPrint = Foundation.DateFormatter()
        dateFormatterPrint.dateFormat = "HH:mm"
        let resultTime = dateFormatterPrint.string(from: date1!)
        print("time:\(String(describing: resultTime))")

getting time as 1: 29 i.e. I am getting wrong time

Please help me to solve this issue.

user2931321
  • 438
  • 1
  • 7
  • 26

3 Answers3

11

use the dateformat

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

instead of

formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ" 

for full code

 let formatter = Foundation.DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" //2017-04-01T18:05:00.000
    let date1  = formatter.date(from: "2017-04-01T18:05:00.000Z")
    print("date:\(String(describing: date1))") 
    formatter.dateFormat = "HH:mm"
    let resultTime = formatter.string(from: date1!)
    print("time:\(String(describing: resultTime))")

option-2

    let formatter = Foundation.DateFormatter()
    formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
    let date1  = formatter.date(from: "2017-04-01T18:05:00.000Z")
    print("date:\(String(describing: date1))")
    formatter.timeZone = TimeZone(abbreviation: "UTC")
    formatter.dateFormat = "HH:mm"
    let resultTime = formatter.string(from: date1!)
    print("time:\(String(describing: resultTime))")

output

enter image description here

Anbu.Karthik
  • 80,161
  • 21
  • 166
  • 138
1

NSLog always prints the date object in GMT timezone, not your local timezone. use your local time zone

suma
  • 9
  • 1
0

Try this Use the timeZone property of the dateFormatter.

let formatter = Foundation.DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ"
let date1  = formatter.date(from: "2017-07-31T11:40:00.000Z")
print("date:\(String(describing: date1))")
let dateFormatterPrint = Foundation.DateFormatter()
dateFormatterPrint.timeZone = TimeZone(abbreviation: "UTC")
dateFormatterPrint.dateFormat = "HH:mm"
let resultTime = dateFormatterPrint.string(from: date1!)
print("time:\(String(describing: resultTime))")
Aravind A R
  • 2,656
  • 1
  • 13
  • 25