Search code examples
swiftdateuidatepickerepoch

strip time off date picker and date off time picker swift


I have two date pickers in my view. One has a mode of date and one has a mode of time. On press of another button I want to be able to grab the values of the date picker and the time picker and combine them into one epoch.

So far I have tried to strip the time off the date picker like so:

let dFormat = DateFormatter()
dFormat.dateFormat = "MMM dd yyyy"
let dateString = dFormat.string(from: datePicker.date)

let dateObj = dFormat.date(from: dateString)
let epochDate = dateObj?.timeIntervalSince1970
print ("date is \(epochDate)")

but I still am getting the current time going along with it. I need it to be 00:00 am because I will then add my epoch val from my secon picker to this in order to get the desired combined epoch


Solution

    • Get the dates from the pickers

      let date1 = datePicker1.date
      let date2 = datePicker2.date
      
    • Get [.year, .month, .day] components from the date picker and [.hour, .minute, .second] from the time picker

      let calendar = Calendar.current
      var dateComponents = calendar.dateComponents([.year, .month, .day], from: date1)
      let timeComponents = calendar.dateComponents([.hour, .minute, .second], from: date2)
      
    • Copy the time components to the date components and create the combined date

      dateComponents.hour = timeComponents.hour
      dateComponents.minute = timeComponents.minute
      dateComponents.second = timeComponents.second
      
      let date3 = calendar.date(from: dateComponents)