Search code examples
iosswiftnsdateformatter

Date will not display correctly


I am trying to make my date display such as "March 2nd, 2018 10:00pm". I tried "MM-dd-yyyy" and "yyyy-MM-dd hh:mm:ss" but it seems like none of these combinations are getting the date I desire.The function to pick the date is sendRequest and it is using a UIDatePicker. enter image description here

 func getCurrentDateTimeFromTimeStamp(timestamp:String)->String{
    let date = NSDate(timeIntervalSince1970:Double(timestamp)!)
    let formatter = DateFormatter()
    formatter.dateFormat = "MMMM d, yyyy HH:mm a"
    return formatter.string(from: date as Date)
}

 let dateCellVar = request.timestamp
    let dateString = dateCellVar.description
    dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timestamp: dateString)

class Request {
var timestamp:Double

init(dict: [String: Any]) {
    self.timestamp = dict["timestamp"] as? Double ?? 0.0
}

 func sendRequest(){
    print("HEY:")
    guard let user = currentUser else { return }
    print("USER: \(user.firstLastName)")

    if let da = dateField.text{
        print(da)
    }
    print(timeField.text)

    print(locationField.text)
    print(messageTextView.text)

    guard let pickedDate = pickedDate else { return print("pickedDate") }
    guard let date = dateField.text else { return print("pickedDate") }
    guard let time = timeField.text else { return print("time") }
    guard let location = locationField.text else { return print("location")}

    let db = Database.database().reference()
    let ref = db.child("requests").childByAutoId()
    let data = [
        "sender": user.uid,
        "recipient": recipientUser.uid,
        "name": user.firstLastName,
        "photoURL": user.photoURL,
        "location": location,
        "date": date,
        "time": time,
        "pickedTimestamp": pickedDate.timeIntervalSince1970,
        "message": messageTextView.text ?? "",
        "status": "PENDING",
        "timestamp": [".sv": "timestamp"]
        ] as [String:Any]

    print("HEYO")
    ref.setValue(data) { error, ref in
        if error == nil {
            print("Success")
        } else {
            print("Failed")
        }
    }


}

Solution

  • Based on your result, your timestamp is in milliseconds, not seconds. You need to divide by 1000.

    You also have the wrong dateFormat. You want to use hh, not HH for the hour. H is for 24-hour time which makes no sense when using a for AM/PM. You should also avoid using dateFormat. Use dateStyle and timeStyle. Let the formatter give you a date formatted best for the user's locale.

    Your code also does a lot of needless conversion. You get your timestamp as a Double and store it as a Double. But then your function to convert the timestamp you expect your number of seconds as a String which you then convert back to a Double. Avoid the needless use of a String.