Dateformatter issue in swift

让人想犯罪 __ 提交于 2021-02-19 09:03:51

问题


My API sending me date string in UTC like 2/20/2016 11:45 AM. For displaying date in my timezone, I am converting date from UTC to Local time zone like below code

    let sourceDateString = "12/20/2016 11:45 AM"
    let formatter = DateFormatter()
     formatter.dateFormat = "MM/dd/yyyy hh:mm a"
     formatter.timeZone = TimeZone(identifier: "UTC")
     let date = formatter.date(from: sourceDateString)

     print(date)

     formatter.timeZone = NSTimeZone.local
     formatter.dateFormat = "MMM dd,yyyy hh:mm a"

     let strDate = formatter.string(from: date!)
     print(strDate)

Above code is working fine if my device time format is in 12 HR but if I am using 24 Hr date from my device then above code is not working. Event it's not able to convert UTC string to date.

Please check above code in the device, it's working fine in simulator.


回答1:


With help of @Martin R, Following code worked for me.

    let sourceDateString = "12/20/2016 11:45 AM"
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy hh:mm a"
    formatter.timeZone = TimeZone(identifier: "UTC")
    formatter.locale = Locale(identifier: "en_US_POSIX")
    let date = formatter.date(from: sourceDateString)

    print(date)

    formatter.timeZone = NSTimeZone.local
    formatter.dateFormat = "MMM dd,yyyy hh:mm a"

    let strDate = formatter.string(from: date!)
    print(strDate)

I forgot to add "POSIX".




回答2:


Code written in Swift 3.0

You need to give local identifier on date formatter.

Here is the following working and tested code.

let sourceDateString = "12/22/2016 09:19 AM"
    let formatter = DateFormatter()
    formatter.dateFormat = "MM/dd/yyyy hh:mm a"
    formatter.locale = Locale(identifier: "en-US")
    formatter.timeZone = TimeZone(identifier: "UTC")
    let date = formatter.date(from: sourceDateString)

    print("\(date)")

    formatter.timeZone = NSTimeZone.local
    formatter.dateFormat = "MMM dd,yyyy hh:mm a"

    let strDate = formatter.string(from: date!)
    print(strDate)

Please let me know if it works.




回答3:


Quick fix for this is to convert 12hr to 24 hr format.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateformatter.dateFormat = @"hh:mm a";
NSDate *date = [dateformatter dateFromString:departTime];
dateformatter.dateFormat = @"HH:mm";
NSString *time24 = [dateformatter stringFromDate:date];
departTimelbl.text=time24;

here you can replace formatter.dateFormat = "MM/dd/yyyy hh:mm a" with formatter.dateFormat = "MM/dd/yyyy HH:mm



来源:https://stackoverflow.com/questions/41277911/dateformatter-issue-in-swift

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