Home > Net >  Date Formatter in Swift is not working properly
Date Formatter in Swift is not working properly

Time:01-09

I am working with dates in Swift. I have to convert from String to Date but some weird stuff is happening. When I run my code on a simulator and pass my date string to formatter, it returns nil. But when I run my code on a physical device it works perfectly.

class ChatViewController: MessagesViewController {
    
    var uid: String
    var isNewConversations:Bool
    private var messages = [Message]()
    private var selfSender: Sender?
    var senderUid: String
    var conversation_Id: String?
    
    public static let dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .long
        formatter.locale = .current
        return formatter
    }()
}

and I am using it like this :

let date = ChatViewController.dateFromatter.date(from: dateString)

My date input in string is: “08-Jan-2023 at 8:57:10 PM GMT 5”

I just debug the whole code but I am not getting what is happening. When I debug it on physical device it works perfectly but when I run it on a simulator it is not working fine, i.e the debugger shows that in 'date' variables you have got nil.

CodePudding user response:

Never use dateStyle and/or timeStyle when parsing a date string. Always use dateFormat. Styles can vary based on the user's locale and other settings on their device. It can also vary based on the user's language.

Since you need to parse a fixed format date string you need to provide a specific date format. You must also use a special locale on the date formatter since your fixed format date string is always in English.

public static let dateFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "dd-MMM-yyyy 'at' h:mm:ss a Z" // Might need O instead of Z at the end.
    return formatter
}()

CodePudding user response:

How about this date formatter:

let customFormatter: DateFormatter = {
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "dd-MMM-yyyy' at 'h:mm:ss a ZZZZ"
    return formatter
}()
  • Related