How to get the date of previous month matching specified day ? [Swift] - ios

How can I get the date of previous month matching specified day ? in Swift
if I have this function getPreviousMonthDate(matchingDay day: Int) -> Date
Examples:
following (dd/mm/yyyy)
If Today is 25/07/2022 and I call getPreviousMonthDate(matchingDay: 27)
: return value would be 27/06/2022 .
If Today is 18/04/2022 and I call getPreviousMonthDate(matchingDay: 14)
: return value would be 14/03/2022 .
If Today is 15/01/2022 and I call getPreviousMonthDate(matchingDay: 16)
: return value would be 16/12/2021 .
and so on...

You can use date components as following:
func getPreviousMonthDate(matchingDay day: Int) -> Date {
let calendar = Calendar.current
let comps = calendar.dateComponents([.year, .month, .day], from: Date())
var comps2 = DateComponents()
comps2.year = comps.year
comps2.month = comps.month! - 1
comps2.day = day
return calendar.date(from: comps2)!
}
I force-unwrapped the date to match your function declaration, I suggest that you deal with the optional dates properly though.

Related

Number of days in month returns wrong value after 10:00 PM

I am having a small issue with getting the total days in a month using Swift.
I have extended the Date class and created this function:
func daysInMonth() -> Int {
print(self.day) ##30
print(self.month) ##12
print(self) ## 2021-11-30 23:46:29 +0000
print(Calendar.current.range(of: .day, in: .month, for: self)?.count) ##31
return Calendar.current.range(of: .day, in: .month, for: self)?.count ?? 0
}
I have set the Date&Time to the 30th of November, at 11:45 PM in the settings of my Mac, in Preferences.
I called the above function at 11:46 PM and obtained the above results (inline, next to the print statements).
The date output is correct as well as the day. The month output is wrong and the result is 31 days in the month of November.
If I run this exact same code before 10:00 PM, I get the right result which is 30 days.
Does anyone know why this is happening?
Thank you,
Paprika
It's a GMT offset issue combined with the current day in a month.
When you create a date without set a day, it will be set to the first day of the month.
So, if your timezone offset is for example -4 means your are 4 hours behind the GMT 0 and by default the timezone defined at Calendar.current is equal the system timezone. So what it means? Means you'll obtain the previous month if you test it in a boundary of 23 + (-4) or the next month if your offset is positive.
You can test this behaviour copying'n paste the following code in the Playground.
func getDaysInMonth(month: Int, year: Int, offset: Int = 0) -> Int? {
let someDate = DateComponents(year: year, month: month, hour: 3)
var current = Calendar.current
let timezone = TimeZone(secondsFromGMT: 60 * 60 * offset)!
current.timeZone = timezone
guard let someDay = current.date(from: someDate) else { return nil }
print("date: \(someDay)") // this will always
return someDay.daysInCurrentMonth
}
for hour in -12...12 {
print("hour: \(hour)\ndays: \(getDaysInMonth(month: 10, year: 2021, offset: hour) ?? -1)")
print("---\n")
}
extension Date {
var daysInCurrentMonth: Int? {
Calendar.current.range(of: .day, in: .month, for: self)?.count
}
}
Notice the days will change starting by your current system time zone (notice only the month will change).
How to fix this?
In your case, I guess you just want to show how many days a month have, so you can just set the to zero like this:
TimeZone(secondsFromGMT: 0)
Do this change at a instance of Calendar.current and check if it works for you.
It appears there something wrong with your Date extension methods for .day and .month.
Without seeing code it's hard to determine what the problem is though. Below is some code for returning the current month (Int) and current numbered day of month (Int)
extension Date
{
var month: Int
{
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.month], from: date)
return components.month
}
var day: Int
{
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.day], from: self)
return components.day
}
}
Please also ensure your time/date settings are correct on your mac/simulator/device. If these are wrong - it could have been jumping to a different month if you were in a timezone that was ahead a few hours.

How to get the today's and tomorrow's date in swift 4

How to get the current date in unix-epoch?
timeIntervalSince1970 prints the current time. Is there any way to get today's time at 12 AM?
For example, The current time is : Jan 7, 2018 5:30 PM. timeIntervalSince1970 will print the current time i.e. 1546903800000.
Current date in epoch system will be Jan 7, 2018 00:00 AM. i.e 1546848000000
This can be done very simply using the following code. No need for date components or other complications.
var calendar = Calendar.current
// Use the following line if you want midnight UTC instead of local time
//calendar.timeZone = TimeZone(secondsFromGMT: 0)
let today = Date()
let midnight = calendar.startOfDay(for: today)
let tomorrow = calendar.date(byAdding: .day, value: 1, to: midnight)!
let midnightEpoch = midnight.timeIntervalSince1970
let tomorrowEpoch = tomorrow.timeIntervalSince1970
I would do this with components.
Assuming you need time in seconds as defined by time(2). If you need in milliseconds as defined by time(3), then you can multiply it out by 1000.
// Get right now as it's `DateComponents`.
let now = Calendar.current.dateComponents(in: .current, from: Date())
// Create the start of the day in `DateComponents` by leaving off the time.
let today = DateComponents(year: now.year, month: now.month, day: now.day)
let dateToday = Calendar.current.date(from: today)!
print(dateToday.timeIntervalSince1970)
// Add 1 to the day to get tomorrow.
// Don't worry about month and year wraps, the API handles that.
let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1)
let dateTomorrow = Calendar.current.date(from: tomorrow)!
print(dateTomorrow.timeIntervalSince1970)
You can get yesterday by subtracting 1.
If you need this in the universal time (UTC, GMT, Z… whatever name you give universal time), then use the following.
let utc = TimeZone(abbreviation: "UTC")!
let now = Calendar.current.dateComponents(in: utc, from: Date())
Use this extension to get today's and tomorrow's date
extension Date {
static var tomorrow: Date { return Date().dayAfter }
static var today: Date {return Date()}
var dayAfter: Date {
return Calendar.current.date(byAdding: .day, value: 1, to: Date())!
}
}
Also try adding following code in date extension:
extension Date
{
var startOfDay: Date
{
return Calendar.current.startOfDay(for: self)
}
func getDate(dayDifference: Int) -> Date {
var components = DateComponents()
components.day = dayDifference
return Calendar.current.date(byAdding: components, to:startOfDay)!
}
}
You can use the following method to get any date by adding days or months or years
by specifying the Calendar Component and the increment value of this component:
func getSpecificDate(byAdding component: Calendar.Component, value: Int) -> Date {
let noon = Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
return Calendar.current.date(byAdding: component, value: value, to: noon)!
}
Where the component wil be one from the following option :
( .day , .month , .year ) and the value will be the amount you want to add for this component
for example to get the next year date you can use the following code:
var nextYear = getSpecificDate(byAdding: .year, value: 1).timeIntervalSince1970

how to get this weekend date in swift? [duplicate]

This question already has answers here:
How do I find the beginning of the week from an NSDate?
(7 answers)
Closed 4 years ago.
If current date is 3 August 2018 (friday), i want to get 4 & 5 august 2018 (saturday and sunday)
if current date is 4 august (saturday), I still want to get 4 & 5 august 2018 (saturday and sunday)
if current date is 6 august (monday) then I want to get 11 & 12 August (saturday and sunday)
how to do that in swift?
Calendar has convenience methods for that
dateIntervalOfWeekend(containing:start:interval:) checks if the given date is in a weekend and returns the startDate and interval(duration in seconds) in the inout parameters. The Bool return value is true if the given date is within a weekend.
nextWeekend(startingAfter:start:interval:) returns startDate und interval in the inout parameters for the upcoming (.forward parameter) or passed (.backward) weekend.
let now = Date()
var startDate = Date()
var interval : TimeInterval = 0.0
if !Calendar.current.dateIntervalOfWeekend(containing: now, start: &startDate, interval: &interval) {
Calendar.current.nextWeekend(startingAfter: now, start: &startDate, interval: &interval, direction: .forward)
}
print(startDate, startDate.addingTimeInterval(interval))
If you need start of Saturday and start of Sunday then replace the last line with
let endDate = startDate.addingTimeInterval(interval-1)
print(startDate, Calendar.current.startOfDay(for: endDate))
Alternatively – suggested by Martin R (thanks) – use dateIntervalOfWeekend(containing:) / nextWeekend(startingAfter:) which both return a DateInterval object containing start, end and duration
let now = Date()
let calendar = Calendar.current
let weekEndInterval = calendar.dateIntervalOfWeekend(containing: now) ?? calendar.nextWeekend(startingAfter: now)!
let startDate = weekEndInterval.start
let endDate = startDate.addingTimeInterval(weekEndInterval.duration-1)
print(startDate, calendar.startOfDay(for: endDate))
let (nextSaturday,orderTotal) = getWeekends()
print(nextSaturday)
print(nextSunday)
func getWeekends() -> (Date,Date) {
let today = Date()
let calendar = Calendar.current
let todayWeekday = calendar.component(.weekday, from: today)
let addWeekdays = 7 - todayWeekday
var components = DateComponents()
components.weekday = addWeekdays
let nextSaturday = calendar.date(byAdding: components, to: today)
components.weekday = addWeekdays + 1
let nextSunday = calendar.date(byAdding: components, to: today)
return (nextSaturday,nextSunday)
}

Date from string is not coming properly and two dates difference also using Swift 3?

I have a date in string format, example:- "2017-07-31" or can be multiple dates (any) in string format. My requirement is to check this date to current date and if it is greater than 0 and less than 15, then that time I have to do another operation.
So first I am converting that date string to in date format. But it is giving one day ago date. Here is my code:
//Date from string
func dateFromString(date : String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let currentDate = (dateFormatter.date(from: date))//(from: date))
return currentDate!
}
Ex. my date is "2017-08-30" and this function is returning 2017-08-29 18:30:00 +0000 in date format. It means 1 day ago. I am little bit confuse about dates operation. I read so many blogs also.
After that I have to check this date to current date if it is in between 0 < 15 than I will do other operation.
Comparing two dates:
extension Date {
func daysBetweenDate(toDate: Date) -> Int {
let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
return components.day ?? 0
}
}
If my date is today date and comparing to tomorrow date then also it is giving 0 days difference. Why?
If – for example – the current date is 2017-07-31 at 11AM then the
difference to 2017-08-01 (midnight) is 0 days and 13 hours, and that's
why you get "0 days difference" as result.
What you probably want is to compare the difference between the start
of the current day and the other date in days:
extension Date {
func daysBetween(toDate: Date) -> Int {
let cal = Calendar.current
let startOfToday = cal.startOfDay(for: self)
let startOfOtherDay = cal.startOfDay(for: toDate)
return cal.dateComponents([.day], from: startOfToday, to: startOfOtherDay).day!
}
}
Try this method for convert string to date:
func dateFromString(date : String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.timeZone = TimeZone.init(abbreviation: "UTC")
let currentDate = (dateFormatter.date(from: date))//(from: date))
return currentDate!
}
Try this to compare the time between two dates in seconds :
var seconds = Calendar.current.dateComponents([.second], from: date1!, to: date2!).second ?? 0
seconds = abs(seconds)
let min = seconds/60 // this gives you the number of minutes between two dates
let hours = seconds/3600 // this gives you the number of hours between two dates
let days = seconds/3600*24 // this gives you the number of days between two dates

check value existence by NSDate as key in dictionary

I have a dictionary like this:
var dic = [NSDate: Int]()
it is used in my iOS to-do app to get the number of finished tasks of a particular date. I only care about the year, month and day sections in NSDate and also want to be able to get the number of tasks in a particular date using this dictionary, how can I do that? thanks.
Instead of storing your date as NSDate in your dictionary you can save it as String so that comparison will be easier. Use following code to store it as a string
func dateFromString(date : NSDate) -> String {
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.stringFromDate(date)
}
You can pass NSDate() to above function and it will give you string containing only year, month and date. For retrieving your data from dictionary use following.
func dateFrom(year:Int, month:Int, day:Int) -> String {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
let gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
let date = gregorian!.dateFromComponents(components)
return dateFromString(date!)
}
You can pass year, month and date to above function and it will return corresponding date in string format. So your dictionary operations will look like
dict[dateFromString(NSDate())] = 1 //for insertion or updation
let numOfTasks = dict[dateFrom(2016, month: 1, day: 15)] //to get task for any particular day
EDIT
If you want to proceed with NSDate as key for your dictionary then you'll have to modify above code as follows. dateFrom will return date with year,month and date of your choice, and time will be some constant value. Time will be set to midnight in your current time zone if you don't set it.
func dateFrom(year:Int, month:Int, day:Int) -> NSDate {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
let gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
let date = gregorian!.dateFromComponents(components)
return date!
}
And for getting current date use following so that you store date object with current year, date, month and time to some constant value.
func getCurrentDate()->NSDate {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day , .Month , .Year], fromDate: date)
return dateFrom(components.year, month: components.month, day: components.day)
}
Usage will be as follows
dict[getCurrentDate()] = i //for insertion or updation
let numOfTasks = dict[dateFrom(2016, month: 1, day: 15)] //to get task for any particular day

Resources