How to get time from YYYY-MM-dd'T'HH:mm:ss.sssZ

我与影子孤独终老i 提交于 2020-05-26 07:45:09

问题


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.


回答1:


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




回答2:


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




回答3:


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))")


来源:https://stackoverflow.com/questions/45409707/how-to-get-time-from-yyyy-mm-ddthhmmss-sssz

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!