Reputation:
I have a value being passed through a UITextField, which is a date value in the format 'Jun 15, 2017' I want to store this value in a variable as a date value that I can use in equations where I add months to it to get some future date, then I want to subtract the future date from today's date to determine the number of days remaining. My research has led me to examples where the values are both date values, but my value is being passed as a string.
Code that sets date value:
let dateFormatter = DateFormatter()
//dateFormatter.dateFormat = "YYYY-MM-DD"
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
termStartDate.text = dateFormatter.string(from: datePicker.date)
self.view.endEditing(true)
Upvotes: 1
Views: 70
Reputation: 93161
If you want to perform date/time calculation, check out the Calendar
structure. Here's an example of how to do calendrical calculations:
let dateStr = "Jun 15, 2017"
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
if let date = dateFormatter.date(from: dateStr) {
let threeMonthFromDate = Calendar.current.date(byAdding: .month, value: 3, to: date)!
let daysRemaining = Calendar.current.dateComponents([.day], from: date, to: threeMonthFromDate).day!
print(daysRemaining)
}
Upvotes: 2