-3

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


}
hg56
  • 185
  • 1
  • 3
  • 16
  • Do not use NSDate. Use Date. (That has nothing to do with the question; it's just a good rule to follow.) – matt Feb 11 '18 at 02:16
  • See: [Date Field SymbolTable.](http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns) Also: [ICU Formatting Dates and Times](http://userguide.icu-project.org/formatparse/datetime) – zaph Feb 11 '18 at 02:39

2 Answers2

4

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • dividing by 1000 did it but the time is still showed as 24 hour format – hg56 Feb 11 '18 at 02:50
  • Did you change to `hh`? Is your device set to 24-hour time? This is why you really should use `dateStyle` and `timeStyle`. Then you get a format appropriate to the user's locale and the user's settings. – rmaddy Feb 11 '18 at 02:52
  • yes I changed it to "yyyy-MM-dd hh:mm a", the device is not set to 24 hour time. – hg56 Feb 11 '18 at 02:55
0

To get the ordinal day, you can use Calendar to extract the day from your Date.

let date = Date()

let calendar = Calendar.current
let dateComponents = calendar.component(.day, from: date)
let numberFormatter = NumberFormatter()

numberFormatter.numberStyle = .ordinal
let day = numberFormatter.string(from: dateComponents as NSNumber)

From there, you'd just code your date format with a DateFormatter and drop in the ordinal date you extracted above, like so:

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "MMMM '\(String(describing: day!)),' yyyy h:mm a"

let dateString = "\(dateFormatter.string(from: date))"

print(dateString)

Additionally, the issue with your year probably stems from the number you're feeding it. timeIntervalSince1970 is expecting whole seconds, so make sure you're feeding it whole seconds.

init(timeIntervalSince1970: TimeInterval) Returns a date object initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds.

Adapted from this answer. Additionally, you may find this site helpful for formatting dates.

Adrian
  • 16,233
  • 18
  • 112
  • 180