Objective-c Why is the following date incorrect - objective-c

I was doing an assignment for my intro to mobile development class.
We had to get the seconds since a date and give how old the person is in seconds, I wanted to extend this and show the actual age of the person. Can achieve this by(check out my code)
When the date is set to the NEXT day so my birthday is tomorrow it is showing an incorrect AGE.
Heres my code;
#import <Foundation/Foundation.h>
int main (int argc, char* argv[]) {
#autoreleasepool {
NSDateComponents* comps = [[NSDateComponents alloc] init];
[comps setYear: 2000];
[comps setMonth: 11];
[comps setDay: 25];
[comps setHour: 17];
[comps setMinute: 50];
[comps setSecond: 01];
NSCalendar* g = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate* dateOfBirth = [g dateFromComponents:comps];
NSDate* now = [NSDate date];
double secondsSince = [now timeIntervalSinceDate:dateOfBirth];
double actualAge = secondsSince / 60 / 60 / 24 / 365;
NSLog(#"\nI am %.9f Seconds Old \nI am Exactly %.9f Years Old %#", secondsSince, actualAge, now);
}
}
Here's my output:
2014-11-24 13:35:23.547 secondsAlive[4978:44040]
I am 441661522.544027984 Seconds Old
I am Exactly 14.004995007 Years Old 2014-11-24 18:35:23 +0000

There is 365.242 days in a year not 365.

Related

Generate consecutive sequence of NSDates

Given some startDate, I would like to degenerate x number of consecutive days after this startDate. I'm attempting to use the following code:
// Generate dates
self.days = [[NSMutableArray alloc] init];
NSDate *startDate = [NSDate date];
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;
for (int i = 1; i < self.mygoal.goalDays; i++) {
[self.days addObject:startDate];
startDate = [theCalendar dateByAddingComponents:dayComponent toDate:startDate options:0];
}
Question: Is the reassignment of startDate ok, given that I'm adding the same object to self.days?
Creating a sequence of dates is not as trivial as it sounds. Actually it is covered in the great WWDC2011 video «Performing Calendar Calculations».
You are adding in every loop a day to the last date. But actually this will fail in timezones with DST if the time is in the hour that is changed for the day of switching and for any following days as the dates will be nil.
If you instead change the date components i the loop and add it to the original satrtdate, it will only effect the day of DST-switching.
To also handle that you can set the hour of the start date to something safe — as noon — as all switches are performed at night hours.
With all this in mind I would use something like this to create a sequence of days with times set to start of day:
NSUInteger numberOfDays = 10;
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *startDate = [cal dateFromComponents:({
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2015;
comps.month = 1;
comps.day = 2;
comps.hour = 12; // for DST-safety
comps;
})];
NSMutableArray *dates = [#[] mutableCopy];
for (NSUInteger i =0 ; i < numberOfDays; ++i) {
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = i;
NSDate *date = [cal dateByAddingComponents:comps
toDate:startDate
options:0];
// set date to beginning of day
[cal rangeOfUnit:NSCalendarUnitDay
startDate:&date
interval:NULL
forDate:date];
[dates addObject:date];
}
So, yes, reassignment is technically OK, but in this particular case it is might cause unexpected trouble.
It's fine because you're not actually adding the same object. dateByAddingComponents: returns a new object, so when you assign it to startDate you are replacing the reference to your old object to a reference to the new one

Instances and Calendar Error? Objective-C

This application is supposed to Log how many seconds it's been since a birthdate(1996) but when I try and log NSLog(#"It has been %f seconds since the start of 1996.", seconds); it logs:
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
my question is why does it print (null)? This is a Objective-C Command Line Tool application in Xcode. Any suggestions would be greatly appreciated! Thanks
Code I'm using:
// main.m
// TimeAfterTime
//
// Created by JP on 1/28/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1996];
[comps setMonth:11];
[comps setDay:7];
[comps setHour:13];
[comps setMinute:23];
[comps setSecond:0];
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *dateOfBirth = [g dateFromComponents:comps];
NSDate *now = [[NSDate alloc] init];
NSLog(#"This NSDate object lives at %p", now);
NSLog(#"The date is %#", now);
double seconds = [now timeIntervalSinceDate:dateOfBirth];
NSLog(#"It has been %f seconds since the start of 1996.", seconds);
}
return 0;
}
The result it prints in the console:
2014-01-29 11:36:15.752 TimeAfterTime[750:303] This NSDate object lives at 0x100103680
2014-01-29 11:36:15.756 TimeAfterTime[750:303] The date is 2014-01-29 16:36:15 +0000
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
Program ended with exit code: 0
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
should be
NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
Due to the wrong initialization, g = nil and thus dateOfBirth = nil.

Get only weekends between two dates

I'm trying get only the Saturdays and Sundays between two dates, but I don't know why get me free days on a week.
Here is my code:
- (BOOL)checkForWeekend:(NSDate *)aDate {
BOOL isWeekendDate = NO;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSRange weekdayRange = [calendar maximumRangeOfUnit:NSWeekdayCalendarUnit];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit fromDate:aDate];
NSUInteger weekdayOfDate = [components weekday];
if (weekdayOfDate == weekdayRange.location || weekdayOfDate == weekdayRange.length) {
// The date falls somewhere on the first or last days of the week.
isWeekendDate = YES;
}
return isWeekendDate;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
NSString *strDateIni = [NSString stringWithString:#"28-01-2012"];
NSString *strDateEnd = [NSString stringWithString:#"31-01-2012"];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [df dateFromString:strDateIni];
NSDate *endDate = [df dateFromString:strDateEnd];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
// int months = [comps month];
int days = [comps day];
for (int i=0; i<days; i++)
{
NSTimeInterval interval = i;
NSDate * futureDate = [startDate dateByAddingTimeInterval:interval];
BOOL isWeekend = [self checkForWeekend:futureDate]; // Any date can be passed here.
if (isWeekend) {
NSLog(#"Weekend date! Yay!");
}
else
{
NSLog(#"Not is Weekend");
}
}
}
The problem:
The issue was caused by NSTimeInterval interval = i; The logic of the for loop was to iterate by days. Setting the time interval to i was iterating by seconds.
From documentation on NSTimeInterval
NSTimeInterval is always specified in seconds;
The answer:
Changing the NSTimeInterval line to
NSTimeInterval interval = i*24*60*60;
Here is a link to another answer I posted on SO (shameless, I know). It has some code that may help you with dates in the future. The methods are implemented as categories of NSDate, meaning they become methods of NSDate.
There are several functions there that help with weekends. But these two might be most helpful:
- (NSDate*) theFollowingWeekend;
- (NSDate *) thePreviousWeekend;
They return the date of the weekend following and prior to the receiver (self).
Generally, you should not use the notion that a day is 86400 seconds, and should use NSDateComponents and NSCalendar. This works even when daylight savings time transitions occur between dates. Like this:
- (NSDate *) dateByAddingDays:(NSInteger) numberOfDays {
NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = numberOfDays;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
return [theCalendar dateByAddingComponents:dayComponent toDate:self options:0];
}
One very important thing to remember is that one day is not (necessarily) equal to 24*60*60 seconds. And you should not do date arithmetic yourself
What you really need to do might seem a little tedious but this is the correct thing to do: use NSCalendar and – dateByAddingComponents:toDate:options:
See Calendrical Calculations guide.

Get an array of future NSDates

I have a date picker.
After choosing a time from this I would like to get the dates of the next 64 Mondays.
How would I go about writing a method to take a date and return an NSArray of NSDates for the next 64 Mondays from that date
for e.g.
I picked time 6:45 pm from date picker then I want to fetch next 64 mondays with there time set to that time.
Example (ARC):
NSDate *pickerDate = [NSDate date];
NSLog(#"pickerDate: %#", pickerDate);
NSDateComponents *dateComponents;
NSCalendar *calendar = [NSCalendar currentCalendar];
dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate];
NSInteger firstMondayOrdinal = 9 - [dateComponents weekday];
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:firstMondayOrdinal];
NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0];
dateComponents = [[NSDateComponents alloc] init];
[dateComponents setWeek:1];
for (int i=0; i<64; i++) {
[dateComponents setWeek:i];
NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0];
NSLog(#"week#: %i, mondayDate: %#", i, mondayDate);
}
NSLog output:
pickerDate: 2011-12-09 20:38:25 +0000
week#: 0, mondayDate: 2011-12-12 20:38:25 +0000
week#: 1, mondayDate: 2011-12-19 20:38:25 +0000
week#: 2, mondayDate: 2011-12-26 20:38:25 +0000
week#: 3, mondayDate: 2012-01-02 20:38:25 +0000
-the remaining 60 here-
Start with the NSDate from the picker, and keep adding 24*60*60 seconds to it until it's a Monday. Add the resulting date to the result. Continue adding 7*24*60*60 seconds to the last date you added and pushing the result onto the return list until you have all 64 Mondays. Here is how you tell if a NSDate falls on Monday:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest];
NSInteger weekday = [weekdayComponents weekday];
if (weekday == 2) ... // 2 represents Monday
EDIT: DaveDeLong pointed out a deficiency in the above algorithm: it will shift the time two times on the days of changing to daylight savings time. Instead of counting seconds manually, use this code to add a day to NSDate:
NSDate *currentDate = [NSDate date];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1]; // Add 1 when searching for the next Monday; add 7 when iterating 63 times
NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0];
[comps release];
You can use NSCalendar to determine what day of the week today (at the chosen time) is; bump it up to get to the next Monday, and then bump that by by 7 days 63 times to get the Mondays you seem to want.

How to set time on NSDate?

I want to set the NSDate time with my desired hours:minutes:seconds
currently im working with NSDate component but it is not giving the desired result
[comps setHour: -hours];
[comps setMinute:0];
[comps setSecond:0];
NSDate *minDate = [calendar_c dateFromComponents:comps];
This works great as an NSDate category.
/** Returns a new NSDate object with the time set to the indicated hour,
* minute, and second.
* #param hour The hour to use in the new date.
* #param minute The number of minutes to use in the new date.
* #param second The number of seconds to use in the new date.
*/
-(NSDate *) dateWithHour:(NSInteger)hour
minute:(NSInteger)minute
second:(NSInteger)second
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components: NSYearCalendarUnit|
NSMonthCalendarUnit|
NSDayCalendarUnit
fromDate:self];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *newDate = [calendar dateFromComponents:components];
return newDate;
}
With the above category, if you have an existing date you want to change the time on, you do so like this:
NSDate *newDate = [someDate dateWithHour:10 minute:30 second:00];
If, however, you are trying to add or subtract hours from an existing date, a category method to do that is also straightforward:
/** Returns a new date with the given number of hours added or subtracted.
* #param hours The number of hours to add or subtract from the date.
*/
-(NSDate*)dateByAddingHours:(NSInteger)hours
{
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hours];
return [[NSCalendar currentCalendar]
dateByAddingComponents:components toDate:self options:0];
}
Your approach should work fine. I needed a solution for this type problem (setting the individual date components) and the following code works as expected for me. My situation: I wanted to create a date object that used the current date but had the time set to a value that was passed in as a string.
NSString *string = #"7:00";
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
NSDateFormatter *timeOnlyFormatter = [[NSDateFormatter alloc] init];
[timeOnlyFormatter setLocale:locale];
[timeOnlyFormatter setDateFormat:#"h:mm"];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *today = [NSDate date];
NSDateComponents *todayComps = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:today];
NSDateComponents *comps = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[timeOnlyFormatter dateFromString:string]];
comps.day = todayComps.day;
comps.month = todayComps.month;
comps.year = todayComps.year;
NSDate *date = [calendar dateFromComponents:comps];
[calendar release];
[timeOnlyFormatter release];
[locale release];
One thing to note is that you really have to pay attention to time zones when you are judging whether a time appears to be accurate. For example, in my app, when you stop at a breakpoint, you will see the time in GMT (so it looks different than the input time, which is in my local time), but when the time is actually displayed on screen in the app, it is being formatted to display in the local timezone. You may need to take this into consideration to determine whether the result is actually different from what you would expect.
If this does not help, can you elaborate on "not giving the desired result"? What result is it giving and how does that compare to what you expected?
is Swift2
extension NSDate {
func dateWithHour (hour: Int, minute:Int, second:Int) ->NSDate?{
let calendar = NSCalendar.currentCalendar(),
components = calendar.components([.Day,.Month,.Year], fromDate: self)
components.hour = hour;
components.minute = minute;
components.second = second;
return calendar.dateFromComponents(components)
}
}
You can set 0 to hour, min, and second.
NSDateFormatter *tFmt = [[NSDateFormatter alloc] init];
tFmt.dateFormat = #"yyyy-MM-dd";
NSString *strNowDate = [NSString stringWithFormat:#"%# 00:00:00",[tFmt stringFromDate:[NSDate date]]];
NSDate *nowDate = [NSDate dateWithString:strNowDate formatString:#"yyyy-MM-dd HH:mm:ss"];
Swift 5 solution (based on #dattk answer) for those who fear Deprecation warnings :)
func date(withHour hour: Int, withMinute minute: Int, withSeconds second: Int) -> Date? {
let now = Date()
let calendar = NSCalendar.current
var components = calendar.dateComponents([.day,.month,.year], from: now)
components.hour = hour
components.minute = minute
components.second = second
return calendar.date(from: components)
}
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
comps.hour = 0;
comps.minute = 15;
NSDate *date = [calendar dateFromComponents:comps];
iOS 8