In my project i want to apply condition like, user can select date only 3months from current date.
I.e i want to display a date picker containing Month and Day with range of 90 days.
Eg. November is going on so only, November December January should be displayed in Date picker for picking.
How can i achieve that??
You can try something like this:
datePicker.maximumDate = Calendar.current.date(byAdding: .month, value: 3, to: Date())
UIDatePicker has minimumDate and maximumDate properties. Use those to set the range of dates you want to allow the user to enter.
Edit:
#wonder posted code to calculate a date 3 months in the future:
futureDate = Calendar.current.date(byAdding: .month, value: 3, to: Date())
Alternately, you could add 90 days to the current date if that's what you want:
futureDate = Calendar.current.date(byAdding: .day, value: 90, to: Date())
Set the datePickerMode to .date to have the user choose only dates, not times.
I don't know how to remove the year selector, although if you select a date range of 90 days that all fall in the same year, they won't be able to select a year other than the current year.
(Note that starting in October, a date range of 90 days includes dates in 2 different years, so you would need the year anyway.)
As wonder said in a comment, you could create your own month and day picker using a UIPickerView, but you would need to add logic to change the number of days based on the month, and exclude days of the current month that are in the past.
Related
I have a time coming from service in string form like so "12:30 PM".
I am able to get this time but I want to add this time in current date. like so
31/3/2021 12:30 PM
The current date is in date object and coming time is in string format.
Please let me know what is a right way to do so? I am right now taking 12, 30,from string and setting it via Calendar. But dont know how to set am pm . Please let me know how to append time with date object. Thanks in advance.
First, if that is the date string you are getting from your service, it is incomplete. It needs a time zone.
Here's what I would do:
Assuming the service always uses the same time zone, find out that time zone.
Create a date formatter for that date string format, including the AM/PM bit.
Set the date formatter to use the time zone from step 1.
Convert the date string to a Date object using your DateFormatter.
Use the current calendar to extract the hours and minutes values into a DateComponents object.
Get the current date, and use the Calendar function date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:) to set the hour and minutes of the current date to the values you got from step 5.
You should search in the Xcode help system for:
Dates and Times (overview)
Calendrical calculations (discussion specific to doing math on dates and times)
DateFormatter. (See this article for info on the characters to use to build your dateFormat string.)
Calendar
DateComponents
Calendar
You can do this by setting up your DateFormatter with the correct timeZone, calendar, defaultDate, and dateFormat. Here's an example:
import Foundation
let parser = DateFormatter()
parser.calendar = Calendar(identifier: .gregorian)
parser.timeZone = TimeZone(identifier: "US/Eastern")!
parser.defaultDate = parser.calendar!.date(
from: DateComponents(
timeZone: parser.timeZone!, era: 1,
year: 2021, month: 3, day: 31,
hour: 12, minute: 0, second: 0))!
parser.dateFormat = "hh:mm a"
print(parser.date(from: "12:30 PM"))
Output:
Optional(2021-03-31 16:30:00 +0000)
In my app I need to group different items based on their date, so I need a method to get date of the beginning of the week, and also a method to find out if two dates are in the same week. However, I get unexpected problems trying to implement this.
I use this code to get the first day of the week:
return Calendar.current.date(from: Calendar.current.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self))
I use Calendar.current, but it returns the same day no matter which day is chosen as the beginning of the week in iOS Settings.
To check if two dates are in the same week I use this code:
func isInSameWeek(date: Date) -> Bool { isEqual(to: date, toGranularity: .weekOfYear) }
Still, Sunday and Monday dates are always considered not in the same week no matter which day is chosen as the beginning of the week in iOS Settings.
How do I fix this? Or maybe it is a normal behavior and this code will work correctly for users in different regions?
You are changing the settings of the Calendar App not the iOS current calendar itself. You need to provide your own app settings to be changed by the user.
var calendar = Calendar.current
calendar.firstWeekday = 2
calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))?.description(with: .current) // "Monday, September 14, 2020 at 12:00:00 AM Brasilia Standard Time"
I want to repeat notifications monthly on a specific day, but my concern is, what if the user chooses the 31? Then the Notification would only fire every 2 months and never in February?
Because the day component would not match.
Is it possible to set the day to the last day of the month, so when for example February is the next month and the user selected the 31. then it would fire on the last day of February?
I could go the non repeating way and add the notifications manually, but then i would have to face the 64 scheduled notification limit.
Thanks for your help in advance.
The Calendar module is the way to go. Handling dates manually can get very tricky.
import Calendar
let selectedDate = "31/01/2020"
// Convert string to Date
let dateF = DateFormatter()
dateF.dateFormat = "dd/MM/yyyy"
let myDate = dateF.date(from: selectedDate)!
// Advancing date by a month, to get end of next month.
Calendar.current.date(byAdding: .month, value: 1, to: myDate) // "Feb 29, 2020 at 12:00 AM"
In the example above, you can see how to advance date by a month.
If the user chooses say the 31 of a month, the calendar automatically calculates the end of the next month accurately, even if it has only 28, 29, 30 or 31 days.
One option would be to use remote notifications and handle them on a server. This would involve a bit more work and a server, but it is more flexible and allows you to change the notifications without the user needing an app update. Link to the Apple Doc for Remote Notifications.
The other option would be the use Calendar.
When you do your logic to send the notification, you can test if today is the last day of the month. If the user chooses to get the notifications on the 31st, and say today is the last day of the month and is the 30th, you can still send the notification because you know there isn't a 31st in this specific month.
I have a Date variable with a person's date birthday. I would like to know how many days remains before this person next birthday. It should be calculated from today date to current year birthday date.
How can this be done with Swift? Also it will be great to consider February 29 in leap years.
To the guys who tried to close this: This is about birthday which has totally different rules from days.
Birthdays are complicated. Your birthday was the date of the moment when you were born, in the timezone where you were born. Considering that Samoa = UTC+14 and Baker Island = UTC-12, it is possible that people born at the same moment in time have birthdays that are two days apart.
So to store somebody's birthday, not the moment of birth, you either store year/month/day, or if you want to store it as a point in time, you store the beginning of that day in UTC, with the understanding that this is to specify a day, and must not be converted to local time.
Now when does your birthday repeat? If the person is born on D/M/Y and D/M is not February 29th, then the next birthday is either D/M/current year or D/M/next year. It is D/M/current year if that date is in the future, otherwise D/M/next year.
If the person is born on February 29th, then you have to determine when officially the next birthday is if the year is not a leap year - this will be February 28th or March 1st, depending on which rules apply.
We also need to clarify what "number of days" means. If my birthday is on April 1st, and now it is March 31st, one second to midnight, my birthday will be one second from now. However, I will assume that the result is supposed to be "one day from now".
So here is the algorithm:
Step 1: Find day/month/year when the person was born.
Step 2: Determine the current time, and convert it to local day/month/year. Determine the current time only once to avoid problems if this calculation is done nanoseconds before midnight.
Step 3: Determine the year when the birthday repeats: If day/month of birthday is greater than current day/month, then the year when the birthday repeats is the current year, otherwise the next year. This is also correct if the birthday was on Feb. 29th.
Step 4: Determine the day/month when the birthday repeats: This is the same as the day/month of the birthday, unless the birthday was on Feb. 29th and the year when the birthday repeats is not a leap year. In that case, the birthday repeats on Feb 28th or March 1st, depending on which rules you decide to apply.
Step 5: Convert the current day/month/year + 12 hours to UTC. Convert the date when the birthday repeats + 12 hours to UTC. Calculate the difference in seconds (which the OS should do for you). Divide by 86,400, then round to the nearest integer. The "+12 hours" and "round to nearest integer" make sure that you have no problems with daylight savings time, leap seconds etc.
Writing this code in Swift or any other language should be no problem.
It depends on what you are looking to use the days value for but here is a small function that will return a Double describing the amount of days until a given Date. Martin R gave a really good answer here and my answer is mainly based on theirs with a little bit of documentation added.
/// This function takes a `Date` parameter and returns an `Int` describing how many days away the `Date` is into the future (accounting for leap years by making 2/29 dates land on 3/1 in non-leap years).
/// - Parameter date: The `Date` object to be evaluated.
func daysUntil(birthday: Date) -> Int {
let cal = Calendar.current
let today = cal.startOfDay(for: Date())
let date = cal.startOfDay(for: birthday)
let components = cal.dateComponents([.day, .month], from: date)
let nextDate = cal.nextDate(after: today, matching: components, matchingPolicy: .nextTimePreservingSmallerComponents)
return cal.dateComponents([.day], from: today, to: nextDate ?? today).day ?? 0
}
Here is my situation, Current Date picker is showing date, month and year in sequence of Date, Month and Year OR Month, Date and Year. But I want to display this sequence as Year first then Month and at last Date.
I searched a lot but same question I found in Javascript but not in iOS, I also searched in Apple Documentation but I didn't find any solution.
How can I achieve this sequence Year, Month and Date? If there any property or method available for DateTime Picker? OR Do I need to use custom picker? if any then which?
Thanks.
The order of year, month and day is depending on the picker's locale.
Eg.
datePicker.locale = NSLocale(localeIdentifier: "zh_TW")
will have different order from
datePicker.locale = NSLocale(localeIdentifier: "en_US")