Home > Software engineering >  How to return a date using dateformatter in Swift?
How to return a date using dateformatter in Swift?

Time:04-01

I have a little problem and I don't know how can I solve it. I have a closedRange of dates which i'm using with a DatePicker.

How can I have a date with that format that I have in the code bellow ?

  var minMaxRange : ClosedRange<Date> {
        return dateStart...dateEnd
    }

I want the datePicker to start from the current date, and dateEnd is coming from the backend. dateEnd is a string so I do not have problem with this.

    var dateStart : Date {
        let isoDate = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = .current
        return dateFormatter.date(from: isoDate)
    }
    
    var dateEnd : Date {
        let isoDate = syncViewModel.schedule[0].end
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        dateFormatter.timeZone = .current
        return dateFormatter.date(from: isoDate) ?? Date.now
    }


CodePudding user response:

You already have a Date... just write var dateStart = Date().

Then, you can format both dates (start and end) to a string when you show them on the screen, using:

dateFormatter.string(from: dateStart)

CodePudding user response:

var minMaxRange: ClosedRange<Date> {
    .now ... dateEnd
}
  • Related