IOS Calculate number of weeks between dates - ios

It is known to calculate the number of years, days, months using NSCalenderUnit type between two days using
dateComponent = [calender components:NSCalendarUnitDay fromDate:startDate toDate:endDate options:0];
totalDays = (int)dateComponent.day;
Anyone suggest How to get total number of weeks?
I have tried using available week units but not met with requirement.
Note: we cant use totaldays / 7.. since If startdate = jan'10'2015 endDate Feb' 02'15 means 22/7 = 3 but actually it is 4.. (Jan 2nd, 3rd,4th week and Feb 1st week.)

Related

Calculate difference between 2 NSDate in year, month, day ignore time?

Giving an example, I have 2 NSDate in the same timezone UTC
NSDate *date1 = [NSDate dateWithString:#"2019-05-31 22:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:#"2019-06-01 01:00:00 +0000"];
I want to make a function to calculate difference between them in Year, month, day ignore time part. Expect result above
Year: 0
Month: 1
Day: 1
Or another example with
NSDate *date1 = [NSDate dateWithString:#"2019-02-28 22:00:00 +0000"];
NSDate *date2 = [NSDate dateWithString:#"2020-03-01 01:00:00 +0000"];
Will get result
Year: 1
Month: 13
Day: 367
I have tried answers in this question How can I calculate the difference between two dates?
But those approach using NSTimeInterval seems not reliable because of 365 or 366 days of year and does not ignore time. Answer like
NSDateComponents *components;
NSInteger days;
components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit
fromDate: date1 toDate: date2 options: 0];
days = [components day];
Give wrong result too.
You could convert each NSDate value to an NSDateComponents value using NSCalendar's componentsInTimeZone:fromDate: method. This will give you the year, month and day values for your two dates, now implement your difference algorithm, which might be:
subtract the earlier date from the larger one - you can determine that based on comparing the two NSDate values
the year difference is just simple subtraction of the year components of the NSDateComponents values
the month difference is the difference between the month components, if this is negative add 12
the day difference is similar but in the negative case you have to add the length of month, which is 28, 29, 30 or 31 - figuring which is left as an exercise :-) (NSCalendar/NSDate Methods should help here)
While this guess at your required algorithm might be wrong, whatever your algorithm you should be able to implement it based on the year, month and day components. HTH
Update
So my first guess at your algorithm was wrong, my second guess is that your three differences; years, months, days; are all meant to be independent approximations of the difference in the corresponding unit. So the year difference ignores the months, days and time; the month difference ignores the days and time; and the days difference ignores the time. This is why 31 May and 1 June are "1 month" apart - the day is ignored. This guess may also be wrong of course but here is how to do it:
order you two dates so the difference is going to be positive.
get just the year, month and day components (or get them all and then discard the others) – this will discard the time component. Use one of NSCalendar's methods to do this.
your year difference is just the difference between the year components
your month difference is the difference between your month components (which could be negative) plus 12 times your year difference
your day difference can be found using components:fromDateComponents:toDateComponents:options: requesting only the day component
[Note: be careful to use the same timezone as the original dates – this is a bit fiddly as you may need to extract it from the date strings yourself (extract the +hhmm and make a time zone). You must remember that an NSDate does not store the time zone, its just an absolute point in time (so equivalent times in different times zones produce the same NSDate value) and for your calculations you want them based on the original time zone as two times one the same day in one timezone can be on different days in a different time zone...). You can set the timezone of an NSCalendar instance or use methods which take timezones when converting from NSDate to NSDateComponents]

How to get start and end dat for week number in objective c

In my iOS app, I have a week number and I need to get the start and end date for that week number.
I'm building an app with which the manager of a company can keep track of the worked hours of staff. These worked hours are processed per day in a custom Registration object.
In this object, the date, begin time, end time and break time are stored and based on those values, the worked hours are calculated.
Then, all Registration objects are stored in a WorkWeek object, containing a week number and an array of registrations. WorkWeek's are constructed based on weeknumbers and run from monday through sunday. In this WorkWeek object, the total worked hours, extra hours and wage are calculated.
Now obviously, I can't reliably calculate extra hours if a Workweek is not a full week that runs from monday through friday. This particularly occurs when the user chooses to get all registrations from a mont from my database. A month does not start on monday and does not end on sunday exactly four weeks later, so i'm dealing with unreliable week object.
Wrapping up
To make sure the information I display in my app is reliable, I need to determine whether a certain week (like week 1 or week 52) contains at least 7 days and, if not, I need to set a bool to FALSE which then triggers a notification to my user.
How can I get the begin and end date of a week based on a weeknumer?
This shows how it could be done:
NSCalendar *cal = [NSCalendar currentCalendar];
// Start of week:
NSDateComponents *comp = [[NSDateComponents alloc] init];
comp.weekday = cal.firstWeekday;
comp.weekOfYear = 1; // <-- fill in your week number here
comp.year = 2015; // <-- fill in your year here
NSDate *startOfWeek = [cal dateFromComponents:comp];
// Add 6 days:
NSDate *endOfWeek = [cal dateByAddingUnit:NSCalendarUnitDay value:6 toDate:startOfWeek options:0];
// Show results:
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateStyle = NSDateFormatterShortStyle;
NSLog(#"%#", [fmt stringFromDate:startOfWeek]);
NSLog(#"%#", [fmt stringFromDate:endOfWeek]);
Some notes:
cal.firstWeekday gives the locale dependent index of the first weekday, e.g.
2 = Monday in Germany, or 1 = Sunday in the U.S. Depending on your needs,
you can also use a constant value here.
It might be necessary to set cal.minimumDaysInFirstWeek, compare
NSDateFormatter reports June 2, 2013 as being in week zero.
The dateByAddingUnit:... method is available in OS X 10.9 or later.
Alternatively, use dateByAddingComponents:....
I have assumed that you use the Gregorian calendar, so that a week has 7 days.
Alternatively, you can add one week and then subtract one day.

Setting and Retrieving Dates in iOS that avoid issues with timezone changes

I have a "time-tracking" app that allows a user to create an entry on whichever days a user desires but only one permitted per day. I store these entries into CoreData.
[rateObject setValue:[Day dateWithHour:currentDate forHour:12] forKey:#"date"];
Later, I retrieve these entries using the following code.
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Day"];
request.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"date" ascending:YES]];
request.predicate = [NSPredicate predicateWithFormat:#"whoWorked == %# && date => %# && date =< %#", whoWorked, [Day dateWithHour:fromDate forHour:0], [Day dateWithHour:toDate forHour:24]];
As you can see I placed the entry in the middle of the day (12 hours) and retrieved the dates from start of the first day (0 hours) and end of the last day (24 hours).
This is a hack which seems to work when I only shift timezones by a few hours or switch for Standard Time to Daylight Savings. It falls apart when I move from NA to Europe i.e. the entries in the old timezone appear on different days in the retrieval.
What I want to get to is an entry made on April 25, 2014 appears on April 25, 2014 no matter what timezone I am currently in.
I have looked at a number of sources to understand NSDate, NSDateComponents, NSCalendar etc but can't seem to land on a good understanding that will allow me to implement this correctly or cleanly. Any advice appreciated.
Here is my method for creating a date with a specific hour (in Day).
+ (NSDate *)dateWithHour:(NSDate *)date forHour:(int)hour {
// Create and initialize date component instance
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit fromDate:date];
if (hour<0) hour = 0;
else if (hour>24) hour = 24;
[dateComponents setHour:hour];
// Create period dates
NSDate *newDate = [[NSCalendar currentCalendar] dateFromComponents:dateComponents];
return newDate;
}
The best to use time-zone and platform independent is the timestamp, which you can get from NSDate as well. With that you can easily do calculations with Time-intervals. If you want to have a specific date it is always related to the time zone of the user. Then you can convert the timestamp into a user-formatted date. Like mentioned by Zaph he might want to see the date where he currently is. Again with the timestamp this is always reliable.
If you want to calculate that an entry can be done only once per calendar day in the location where somebody is, then you can calculate with ˙NSCalendar˙ and ˙NSDateComponents˙ for example what day a timestamp represents and then from the beginning of that day calculate 24 hours up. Conversion back to a timestamp gives you a helpful range for check if something is within the same calendar day. The NSCalendar is the base for calculation even if you will probably use Gregorian most of the time. With the NSDateComponentsyou can what ever part you want from your Timestamp (e. g. only the day, the month, the year, etc.).

Seconds Until a Specified Day of the Week

I am having some trouble calculating the number of seconds until a specified day of the week.
For example, calculate the number of seconds until Sunday from the current time in seconds.
The calculation must be dynamic so it is compatible for every Sunday.
Is there any way to accomplish this without specifying a specific date?
You need to use NSCalendar and NSDateComponents. See the code example below. Make sure to set the calendar to "gregorian" if you want the correct 7 day week for the US.
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags = NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];
// Just a test line for your benefit.
NSLog(#"%li %li %li %li",(long)comps.weekday,(long)comps.hour, (long)comps.minute, (long)comps.second);
// I did this kinda fast - check it over good. Will need some sort of if statement in case the current day is Sunday (7)
NSInteger sec = (60 - comps.second) + (60 - comps.minute)*60 + (24 - comps.hour)*3600 + (6 - comps.weekday)*24*60*60;
NSLog(#"%li",sec);
You will have to modify this somewhat for your use. For instance if you want the day of the week to be a variable, etc. but this should get you on the right track.
Hope this helps. Good luck.
EDIT
See Duncan's remarks below for a better way to actually calculate the seconds.
The NSCalendar class has a whole bunch of methods for this sort of thing. Do a search on "Calendrical calculations" in Xcode for more information.
You'll need a Gregorian NSCalendar (or other type for other calendars like the Chinese, Arabic, Hebrew calendar) NSDates, and NSDateComponents objects.
Look at the method components:fromDate:toDate:options: in particular.
EDIT: That'll teach me to leave an answer unfinished and go do the dishes.
One difference from Dylan's post, though: I would take the current NSDate, convert it to components, then set the day-of-week to the desired future day of week, then convert back to an NSDate, and finally take the difference between the two dates using the NSDate method timeIntervalSinceDate.

Compute number of weeks since epoch more accurately than days/7

I'm putting together a game where there's a tournament every week, and every week there's a different special bonus for the game.
To make this work I need to know which week it is so I can select the right bonus, and make sure the score goes to the right tournament.
A trivial answer is to take the number of days since epoch, offset to get to a monday, then compute the number of days and divide by 7. Obviously this fails because of leap year.
Another option would be to figure out which week of the year you're on, but that gets weird when you transition from one year to the next. Also, the tournament ends at the end of the day on Sunday, so it doesn't follow the normal week borders.
I was about to start doing some fairly complicated stuff using the year, day of year and day of week to try to figure it out, but I thought I'd ask here in case there was an easy solution I was missing.
This will be done in Objective-C on iOS.
This should work:
// Choose any reference date which is a Monday:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *refComp = [[NSDateComponents alloc] init];
refComp.year = 1970;
refComp.month = 1;
refComp.day = 5;
NSDate *refDate = [cal dateFromComponents:refComp];
// Compute number of weeks between your date and the reference date:
NSDateComponents *comp = [cal components:NSCalendarUnitWeekOfYear fromDate:refDate toDate:yourDate options:0];
NSInteger weeks = comp.weekOfYear;
But calculating the number of days (since some Monday) and dividing by 7 should
give the same result because every week has 7 days, regardless of leap years.

Resources