title: Start and End date of month in SwiftUI
body: <p><strong>How to get startDateOfMonth and endDateOfMonth based on selected date in SwiftUI?</strong></p>
  
  <p>I have found some answers for Swift (DateComponents), but couldn't make it work with SwiftUI.</p>
  
  <p>Why I need this: I am going to use dynamic filters using predicate to filter all the data in the currently selected month (using custom control to switch months). But first I need to get the start and end dates per selected month.</p>
  
  <p>EXAMPLE code:</p>
  
  <p><strong>ContentView.swift</strong></p>
  
  <pre><code>import SwiftUI
  
  struct ContentView: View {
  
      @State var currentDate = Date()
  
      // How to make startDateOfMonth and endDateOfMonth dependent on selected month?
      @State private var startDateOfMonth = "1st January"
      @State private var endDateOfMonth = "31st January"      
  
      var body: some View {
  
          VStack {
              DateView(date: $currentDate)
  
              Text("\(currentDate)")
  
              Text(startDateOfMonth)
              Text(endDateOfMonth)
  
          }
  
      }
  }
  
  struct ContentView_Previews: PreviewProvider {
      static var previews: some View {
          ContentView()
      }
  }
  </code></pre>
  
  <p><strong>DateView.swift</strong></p>
  
  <pre><code>import SwiftUI
  
  struct DateView: View {
      static let dateFormat: DateFormatter = {
          let formatter = DateFormatter()
          formatter.setLocalizedDateFormatFromTemplate("yyyy MMMM")
          return formatter
      }()
  
      @Binding var date : Date
  
      var body: some View {
  
          HStack {
  
              Image(systemName: "chevron.left")
                  .padding()
                  .onTapGesture {
                      print("Month -1")
                      self.changeDateBy(-1)
              }
  
              Spacer()
  
              Text("\(date, formatter: Self.dateFormat)")
  
              Spacer()
  
              Image(systemName: "chevron.right")
                  .padding()
                  .onTapGesture {
                      print("Month +1")
                      self.changeDateBy(1)
              }
  
          }
          .padding(EdgeInsets(top: 5, leading: 10, bottom: 5, trailing: 10))
          .background(Color.yellow)
      }
  
      func changeDateBy(_ months: Int) {
          if let date = Calendar.current.date(byAdding: .month, value: months, to: date) {
              self.date = date
          }
      }
  }
  
  struct DateView_Previews: PreviewProvider {
  
      struct BindingTestHolder: View {
          @State var testItem: Date = Date()
          var body: some View {
              DateView(date: $testItem)
          }
      }
  
      static var previews: some View {
          BindingTestHolder()
      }
  }
  </code></pre>