Reputation: 35
i am trying to calculate the time between two dates. One of the dates is today and the other date is somewhere in the future.
The issue is the date in future is separated into two string, the first containing the date and the other containing the time for that date. When i put the two strings together to a single string and try to convert it to a NSDate i get Nil.
I assume there is something wrong with my date variable.
let eventDate: String? = "21 Aug Sun 2016"
let eventTime: String? = "9:00 PM"
let date : String? = "\(eventDate!) \(eventTime!)"
print(date!) // "21 Aug Sun 2016 9:00 PM"
let formatter = NSDateFormatter()
formatter.dateFormat = "dd MMM eee yyyy HH:MM a"
formatter.AMSymbol = "AM"
formatter.PMSymbol = "PM"
if let dateTimeForEvent = formatter.dateFromString(date!) {
print(dateTimeForEvent)
}else {
print("Error")// prints error
}
Upvotes: 1
Views: 52
Reputation: 63399
Your primary issue is that you're using HH
, which is for 24-hour time, instead of hh
, and MM
(which is for month) instead of mm
. Try this:
import Foundation
let eventDate = "21 Aug Sun 2016"
let eventTime = "9:00 PM"
let eventDateTime = "\(eventDate) \(eventTime)"
print(eventDateTime) // "21 Aug Sun 2016 9:00 PM"
let formatter = NSDateFormatter()
formatter.dateFormat = "dd MMM eee yyyy hh:mm a"
if let date = formatter.dateFromString(eventDateTime) {
print(date) // 2016-08-21 21:00:00 +0000
}
else {
print("Error")// prints error, no shit? why is this comment here?
}
Side notes:
date
, if it's a String?
?date
an optional, anyway? You assigned it a literal value.AMSymbol
and the PMSymbol
. Those only pertain to printing dates, not parsing them.Upvotes: 2
Reputation: 318955
Two things:
h:mm a
. HH
is for a two-digit, 24-hour hour. You have a 1 or 2 digit, 12-hour hour. And MM
is for a 2-digit month. Use mm
for a two-digit minute.nil
date on any device using a language other than English.Upvotes: 2