Home > database >  why i get an error in the date formatter code?
why i get an error in the date formatter code?

Time:02-17

I’m trying to convert my AM PM time pickers to 24h format to print the start and end time to calculate the price but i got an unknown error. attached is photo of my UI to simplify the idea and my code. Note: the end time is automatically shows after i choose the start time My UI

@objc func donePressed(){
  // formatter
  let formatter = DateFormatter()
  formatter.dateStyle = .none
  formatter.timeStyle = .short
           
  startTimeTxt.text = formatter.string(from: StartTimePicker.date)
  self.view.endEditing(true)
           
  endTimeTxt.text = formatter.string(from: EndTimePicker.date)
  self.view.endEditing(true)
        
  let starttimecal = StartTimeTxt.text!
  let endtimecal = EndTimeTxt.text!
        
  let StartTo24 = starttimecal
  let EndTo24 = endtimecal
  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat = "h:mm a"

  let sTime = dateFormatter.date(from: startTo24)
  dateFormatter.dateFormat = "HH:mm"
  let sTime24 = dateFormatter.string(from: sTime!)
  print("24 hour formatted Date:", sTime24)
  let eTime = dateFormatter.date(from: endTo24)
  dateFormatter.dateFormat = "HH:mm"
  let eTime24 = dateFormatter.string(from: eTime!) // here the fatal error comes after i choose the start time from simulator 
  print("24 hour formatted Date:", eTime24)
}

CodePudding user response:

To get the 12h time format to display in the text fields you can use the formatter you already have but I also like to set the locale

let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"

To calculate the time difference there is a function for that in the Calendar class, here we calculate the number of hours and minutes between two dates (this is an assumption since I don't know exactly what calculation you want to do)

let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)

Below is a more complete example

//Sample data
let startDate = Date()
let endDate = startDate.addingTimeInterval(3.25*60*60) //add 3h and 15 minutes

// Format and print in 12h format
let dateFormatter12h = DateFormatter()
dateFormatter12h.locale = Locale(identifier: "en_US_POSIX")
dateFormatter12h.dateFormat = "h:mm a"
let start = dateFormatter12h.string(from: startDate)
let end = dateFormatter12h.string(from: endDate)
print(start, end)

// Calculate time difference in hours and minutes
let hourAndMinutes = Calendar.current.dateComponents([.hour, .minute], from: startDate, to: endDate)
print(hourAndMinutes)

// Calculate price, the formula is just an example
let price = hourAndMinutes.hour! * 15   hourAndMinutes.minute! * 15 / 60
print(price)

Output

6:46 PM 10:01 PM
hour: 3 minute: 15 isLeapMonth: false
48

  • Related