Home > Enterprise >  Change day but keep time from saved date time
Change day but keep time from saved date time

Time:02-15

I have a DatePicker in Swift that saves to CoreData once the user saves their changes.

When saving it, it stores the date and time into the model.

I'm using only the time when displaying data to the user so I didn't run into issues before about dates.

However, I am now using the saved time in a MSGraph network call, but unfortunately the date is sent too in the call.

This has caused the date time to be historical rather than "today but this set time".

Is there an easy way to let the time picker set the date to today, but let the time be settable?

Without adding too much arbitrary code:

struct ContentView: View {

 @State var currentTime: Date = Date()
 let myModel: Model

 var body: some View {

  DatePicker("Time", selection: $currentTime, displayedComponents: .hourAndMinute)
   .onAppear {
    currentTime = myModel.savedTime ?? Date() // because Core Data is optional
   }

  Button {
   myModel.savedTime = currentTime
   CoreDataManager().save()
  } label: {
   Text("Save time")
  }

 }
}

I've been trying to work with the myModel.savedTime = currentTime line where I manipulate the currentTime before it is sent to the CoreDataManager for updating to the CoreData model, but haven't been able to get it to work correctly.

I was using this extension:

extension Date {
 func setTimeToToday() -> Date {
  let components = Calendar.current.dateComponents(
   [.hour, .minute, .second],
   from: self
  )
  return Calendar.current.nextDate(
   after: self,
   matching: components,
   matchingPolicy: .nextTime,
   direction: .forward
  )!
 }
}

And running it by doing: myModel.savedTime = currentTime.setTimeToToday()

I'm using iOS 14 if it helps with minimum compatibility.

CodePudding user response:

The picked time you save in Core Data will always be from the date the picker was used.
But you can recalculate those times to "today" before you make your network call:

// the saved date, here dummy
var myDate = Date.now - 24*60*60*5
print(myDate)

// extract hour & minute
let components = Calendar.current.dateComponents([.hour, .minute], from: myDate)
let hour = components.hour ?? 0
let minute = components.minute ?? 0


// get today and apply saved hour & minute
var newComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: Date.now)
newComponents.hour = hour
newComponents.minute = minute
let newDate = Calendar.current.date(from: newComponents) ?? Date.now

print(newDate)
  • Related