How to set maximum date in UIDatePicker? - ios

I am trying to create UIDatePicker in my project which maximum date should be that of yesterday instead of current date. Is there a way to set selected date as yesterday instead of selecting current date?

Use maximumDate property of your date picker.
let yesterdayDate = Calendar.current.date(byAdding: .day, value: -1, to: Date())
yourPicker.maximumDate = yesterdayDate

you can use below code to achieve this
let calender = Calendar.current
let date = Date()
let finalDate = calender.date(byAdding: Calendar.Component.day, value: -1, to: date)
if let FinalDate = finalDate{
yourPicker.maximumDate = FinalDate
}

Related

How do i know if a specific date is a month, or a week to an parent date?

Lets say i have a program that reminds users of their appointments , from the current date until the date of the appointment, i want to find out if a particular date is a week to the appointment or a month to the appointment .
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
var newDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
if newDate is a month to endDate {
//schedule reminder
}
if newDate is a week to endDate{
//schedule reminder
}
how can i check if the current date is a week/month to the appointment ?
You don't need to use any date comparison, you can simply generate the notification dates using Calendar.date(byAdding:value:to:) and just passing the correct components. To set the date 1 week/month before endDate, pass -1 to value.
let oneWeekBeforeAppointment = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: endDate)!
let oneMonthBeforeAppointment = Calendar.current.date(byAdding: .month, value: -1, to: endDate)!
Try this to calculate the duration in days
func DateFormat() -> DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
return dateFormatter
}
var appointementDate: Date?
var today = Date()
appointementDate = DateFormat().date(from: "22/02/2020")
today = DateFormat().date(from: DateFormat().string(from: today))!
let timeInterval = Int(exactly: (today.timeIntervalSince(appointementDate!))) ?? 0
print("\(timeInterval/86400) days left")

How to get next n days date from the given date

I am able to next 15 days date from current date, but when i tried to give custom date instead of current date, it not working.
let date = sharedAppDelegate.dueDate
let givenDate = Utility.convertStringToDate(format: "yyyy-MM-dd",
dateString: date)
let futureDate = (givenDate as NSCalendar).date(byAdding: dateComponents, to: Date()) ?? Date()
Third line gives error like Date? is not convertible to NSCalendar.
Expected result:- futureDate should be next 15 date from givenDate
A Date is not a Calendar
You can use the Calendar to do calculations or comparisons on Date objects, in your case you want to use the Calendar to add x number of days to your starting date
Try
let startDate = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: startDate)
print(tomorrow)
OUTPUT:
Optional(2019-06-01 07:14:48 +0000)
You can extend Date class like this.
extension Date {
func dateByAddingDays(dateNum:Int) -> Date {
return Calendar.gregorian.date(byAdding: .day, value: dateNum, to: self)!
}
}
Now create date object
let today = Date()
let dayAfterTomorrow = today.dateByAddingDays(dateNum:2)
debugPrint(dayAfterTomorrow)

issues in comparing Day from Date in swift 4

Comparison is required to check date is past date day.
I have tried with this
let calendar = NSCalendar.current
//Get just MM/dd/yyyy from current date
let components = calendar.dateComponents([], from: Date())
//Convert to NSDate
let pastDates = self.calendar.selectedDates.filter { $0 < calendar.date(from: components as DateComponents)! }
Update the below line to give you a date object,
let components = calendar.dateComponents([.month, .day, .year], from: Date())
Currently you are not providing any date component in the array so you will not get a date object.
I didn't understood what is your question properly, but hope this helps you:
let beforeDateStr = "04/12/2018"
let todayDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
let beforeDateFormatted = dateFormatter.date(from: beforeDateStr)
if Calendar.current.compare(todayDate, to: beforeDateFormatted!, toGranularity: .day) == .orderedDescending {
print("before date day is lesser than current date")
} else {
print("before date day is equal or greater than todays date")
}
To find the date is smaller or bigger:
You can use this simple Code:
let differenceBetweenTwoDate = Calendar.current.dateComponents([.day], from: previousDate, to: Date())
if differenceBetweenTwoDate.day! > 0{
print("date is bigger")
}else{
print("date is smaller")
}
Hope it Helps!
This is how you can add hours or days in current date and time -
calendar.date(byAdding: .hour, value: 1, to: currentDate)
calendar.date(byAdding: .day, value: 7, to: currentDate)
And this is how you can compare 2 dates and calculate hours, mins and also days
let calendar = Calendar.current
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let anyDataTime = dateFormatter.date(from: anotherDateTime)
let components = calendar.dateComponents([.minute], from: Date(), to: anyDataTime!)
let hour = (Double(components.minute!) / 60.0).rounded()

Restricting enabled time to a specific time span in UIDatePicker swift 4

I'm trying to restrict the time of a datePicker from 09:00 AM to 09:00 PM (21:00) with a time interval of 30 minutes. I have tried all known means for that and have been searching the internet for a long time. But I found nothing.
Here is the code I wrote
//datePicker.setDate(dateFormatter.date(from: "09.00")!, animated: true)
datePicker.maximumDate = Calendar.current.date(byAdding: .hour, value: -12, to: dateFormatter.date(from: "21.00")!) //)Calendar.current.date(byAdding: Calendar.Component.hour, value: 1, to: Date())
datePicker.minimumDate = Calendar.current.date(byAdding: Calendar.Component.hour, value: -12, to: dateFormatter.date(from: "09.00")!)
But it didn't work. Please help.
Restricting user so she/he can only pick date between 9 and 12 but will show all the available options as this is date picker view's default behaviour but by setting proper minimumDate and maximumDate user can only pick between 9 and 21. Try below code and let me know if it works
And if you want to display times of your choice I will suggest better create an array of times you want to display, So user will only choose from the array you will provide In this case times between 9 am and 9 pm like [9:00,9:30,10:00,10:30,.....,21:00] and set that array to normal picker
datePicker.datePickerMode = .time // setting mode to timer so user can only pick time as you want
datePicker.minuteInterval = 30 // with interval of 30
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm"
let min = dateFormatter.date(from: "9:00") //createing min time
let max = dateFormatter.date(from: "21:00") //creating max time
datePicker.minimumDate = min //setting min time to picker
datePicker.maximumDate = max //setting max time to picker
The values you want to put in minimumDate and maximumDate are 9am and 9pm of the current date. The current date is what is missing in your code
let cal = Calendar.current
let now = Date() // get the current date and time (2018-03-27 19:38:44)
let components = cal.dateComponents([.day, .month, .year], from: now) // extract the date components 28, 3, 2018
let today = cal.date(from: components)! // build another Date value just with date components, without the time (2018-03-27 00:00:00)
datePicker.minimumDate = today.addingTimeInterval(60 * 60 * 9) // adds 9h
datePicker.maximumDate = today.addingTimeInterval(60 * 60 * 21) // adds 21h
Did you try to achieve this from storyboard?
try following configuration:
from code:
let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.day, .month, .year], from: Date())
dateComponents.setValue(9, for: .hour)
let minDate = Calendar.current.date(from: dateComponents)
dateComponents.setValue(21, for: .hour)
let maxDate = Calendar.current.date(from: dateComponents)
self.datePicker?.minimumDate = minDate
self.datePicker?.maximumDate = maxDate
self.datePicker?.minuteInterval = 30
Try this:
let now = Date()
datePicker.datePickerMode = .time
datePicker.minimumDate = Calendar.current.date(bySettingHour: 9, minute: 0, second: 0, of: now)
datePicker.maximumDate = Calendar.current.date(bySettingHour: 21, minute: 0, second: 0, of: now)
datePicker.minuteInterval = 30

Swift Datepicker with minimum date

Goord Morning all together,
i have an app with ios 8 and swift.
in there is a UIViewcontroller within a UIDatepicker
I set a minimum date. for example the date of today: 2 | May | 2015
with this solution it should not be possible to set a date which is in the past
but if would like to set this date 15 | January | 2016
i set at first the day to 15
than the month to january but then the UIDatepicker goes back to the minimum date 2 May 2015
is it be possible, that wenn change the day to 15 and the month to january, that the year changes automaticly to 2016?
Let your minimumDate unset and try to configure it by code...
Try this:
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = NSDate()
let nowCalendar = NSCalendar.currentCalendar()
let nowComponents = nowCalendar.components([.Day, .Month, .Year], fromDate: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compareDate(sender.date, toDate: now, toUnitGranularity: [.Day, .Month, .Year]) == NSComparisonResult.OrderedAscending
{
let dateCalendar = NSCalendar.currentCalendar()
let dateComponents = dateCalendar.components([.Day, .Month, .Year], fromDate: sender.date)
dateComponents.year = nowComponents.year + 1
let newDate = dateCalendar.dateFromComponents(dateComponents)
sender.date = newDate!
}
}
///Swift4 Version - I think it may works with 3 too.
#IBAction func changeValue(sender: UIDatePicker)
{
//Get time Now, and convert to a NSCalendar
//Specify the minimun date if you want.
let now = Date()
let nowCalendar = Calendar.current
let nowComponents = nowCalendar.dateComponents([.day, .month, .year], from: now)
//Compare if date is lesser than now and then create a new date
if nowCalendar.compare(sender.date, to: now, toGranularity: Calendar.Component.day) == ComparisonResult.orderedAscending
{
var dateCalendar = Calendar.current
var dateComponents = dateCalendar.dateComponents([.day, .month, .year], from: sender.date)
guard let year = nowComponents.year else { return }
dateComponents.year = year + 1
let newDate = dateCalendar.date(from:dateComponents)
sender.date = newDate!
}
}
I published a complete example working in playground if you wish to play a little.
https://gist.github.com/dedeexe/4878f78d7e1d5fe8b372ef84de629b59
For swift 4:
I have like this.
1. My function:
func AddDaysToToday(days: Int) -> Date? {
var dateComponents = DateComponents()
dateComponents.day = days
return Func.GetCalendar(tz: .utc).date(byAdding: dateComponents, to: Date()) //you can return your own Date here.
}
In my VC:
let today = DateFunc.AddDaysToToday(days: 0)
datePicker.minimumDate = today

Resources