Difference in hours between two NSDate - iphone

Here I'm trying to calculate the hours between two dates. When i run the application, it crashes. Could you please tell me the mistake in this code?
NSString *lastViewedString = #"2012-04-25 06:13:21 +0000";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss zzz"];
NSDate *lastViewed = [[dateFormatter dateFromString:lastViewedString] retain];
NSDate *now = [NSDate date];
NSLog(#"lastViewed: %#", lastViewed); //2012-04-25 06:13:21 +0000
NSLog(#"now: %#", now); //2012-04-25 07:00:30 +0000
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:lastViewed];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSLog(#"hoursBetweenDates: %#", hoursBetweenDates);

Referring to this answer of a mostly similar question a better and Apple approved way would be using the NSCalendar methods like this:
- (NSInteger)hoursBetween:(NSDate *)firstDate and:(NSDate *)secondDate {
NSUInteger unitFlags = NSCalendarUnitHour;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:firstDate toDate:secondDate options:0];
return [components hour]+1;
}
If you target iOS 8 or later use NSCalendarIdentifierGregorian instead of the deprecated NSGregorianCalendar.

I think difference should be in int value...
NSLog(#"hoursBetweenDates: %d", hoursBetweenDates);
Hope, this will help you..

NSInteger can't be shown by using
NSLog(#"%#", hoursBetweenDates);
instead use:
NSLog(#"%d", hoursBetweenDates);
If unsure what to use look in the Apple Developer Docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265

Related

How To Get The Current Date From Device?

I am facing a weird problem with NSDate, when I try fetch a date from device, sometimes it shows previous month for some versions
Here is my chunk of code for reference
NSDate *date = [NSDate date];
NSDateFormatter *dateF = [[NSDateFormatter alloc]init];
[dateF setDateFormat:#" dd.MM.yyyy "];
NSString *selectedDate = [dateF stringFromDate:date];
Any inputs are appreciated, Thank you
To avoid later localizing problems you might use NSCalendar and its method components:fromDate:
Something like this:
NSCalendar * calendar = [NSCalendar currentCalendar];
NSDateComponents * components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:[NSDate date]];
NSString * stringDate = [NSString stringWithFormat:#"%d.%d.%d", components.day, components.month, components.year];
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"hh:mma dd/MMM"];
NSString *dateString = [dateFormat stringFromDate:today];
NSLog(#"date: %#", dateString);
[dateFormat release];
This is an example by Apple so it looks like you have your upper-case / lower-case right
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd 'at' HH:mm"];
Are you sure your device's date is set right? Also have you tried setting the locale of the NSDateFormatter?
EDIT:
To address you question in comments: NSDate is a point in time irrespective of time zones, calendars and so so on. NSCalendar and NSDateFormatter allow you to convert this point in time into a representation that is correct in a given time zone, with a given calendar.

How to retrieve a date for a given weekday in iOS?

I want to find a date by providing a weekday. For instance, I want to find the date of last Sunday and this Sunday. How to do it in iOS?
In OSX, NSDate provides a method of dateWithNaturalLanguageString, but iOS does not provide a similar method. Please help me.
Thanks.
you can calculate using NSDateComponents..
This is Sample. It helps you.
NSDate *date = [NSDate date];
NSString *dateString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterLongStyle
timeStyle:NSDateFormatterNoStyle];
NSString *timeString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
int weekday = [[currentCalendar components:NSWeekdayCalendarUnit fromDate:date] weekday];
NSString *weekdayString = [[[NSDateFormatter alloc] shortWeekdaySymbols] objectAtIndex:weekday-1];

how to add the time in iphone?

I have three string
str1 = #"00:14";
str2 = #"00:55";
str3 = #"00:10";
i need to add the three string as a integer and display in the same time format
how can i do please help me
Thanks in Advance
Working with dates in Cocoa is fun! You could create a method like this:
- (NSDate *)dateByAddingDates:(NSArray *)dates {
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [dates objectAtIndex:0];
for (int i = 1; i < [dates count]; i++) {
NSDate *newDate = [dates objectAtIndex:i];
NSDateComponents *comps = [calendar components:unitFlags fromDate:newDate];
date = [calendar dateByAddingComponents:comps toDate:date options:0];
}
return date;
}
And use it like this:
NSString *str1 = #"00:14";
NSString *str2 = #"00:55";
NSString *str3 = #"00:10";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"mm:ss"];
NSArray *dates = [NSArray arrayWithObjects:[dateFormatter dateFromString:str1],
[dateFormatter dateFromString:str2],
[dateFormatter dateFromString:str3], nil];
NSDate *date = [self dateByAddingDates:dates];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
To do things properly, it would be this:
Use an NSDateFormatter to convert the strings into NSDate objects.
Use [NSCalendar currentCalendar] to extract the NSDateComponents for each date, particularly the NSMinuteCalendarUnit.
Add up all the minutes of the date components, and set that into an NSDateComponent object
(optional) Use your calendar to convert the NSDateComponent back into an NSDate.
To do things stupidly, you'd get a substring of characters after :, invoke intValue on it to turn the string into an int, then add it all up. I don't recommend doing this, because it could lead to subtle and devious errors. Plus, there's already code in place to do it for you. :)
check out this related thread: Comparing dates
in summary, first parse the strings as NSDates using the initWithString: method call. Thereafter you can add and manipulate the dates any way you wish, and finally just format it for the right output.
Hope this hopes clarify your query.
Btw the Mac Developer SDK Reference can found here for your information:-
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDate

how to find the date for the 3rd day from the current date iphone/ipad

Can any one tell that how to find the date for the 3rd day from the current date iphone/ipad.
Thanks in advance
You can use this:
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:3];
NSDate *threeDaysFromToday = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
Slightly modified example from Apple's own documentation on NSDate. Check the link out for further info and more examples.
Here is Sample Code
NSDate * currentDate=[NSDate date];
NSTimeInterval interval=[currentDate timeIntervalSince1970];
NSTimeInterval intervalForThirdDate=interval+86400*3;
NSDate *nextDate=[[NSDate alloc]initWithTimeIntervalSince1970:intervalForThirdDate];
NSDate *today = [NSDate date];
NSTimeInterval threeDays = 86400*3;
NSDate *threeDaysFromToday = [NSDate dateWithTimeInterval:threeDays sinceDate:today];
choose one:
NSDate *futureDate;
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:3];
futureDate = [[NSCalendar currentCalendar] dateByAddingComponents:components toDate:[NSDate date] options:0];
NSLog(#"%# - %#", [NSDate date], futureDate);
NSDate *futureDate = [[NSDate date] dateByAddingTimeInterval:3 * (24*60*60)];
[NSDate dateWithTimeIntervalSinceNow:86400*3]
But as someone mentioned above, DST might make this too inaccurate. Depends on how important that is.
Something like:
// get the gregorian calendar ready to go; use the getter for the current system
// calendar if you're happy to deal with other calendars too
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier: NSGregorianCalendar];
// get an NSDate object that is three days in the future
NSDate *dateInFuture = [NSDate dateWithTimeIntervalSinceNow:3*24*60*60];
// grab the date components for the bits we want to print in this example
NSDateComponents *componentsOfDateInFuture =
[gregorianCalendar
components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
fromDate:dateInFuture];
// and print
NSLog(#"in three days it'll be %04d/%02d/%02d",
componentsOfDateInFuture.year,
componentsOfDateInFuture.month,
componentsOfDateInFuture.day);
// clean up
[gregorianCalendar release];
EDIT: Pablo Santa Cruz's answer is better for ensuring you're three days in the future, given daylight savings concerns. This is how you'd decompose an NSDate to day/month/year though, for the purposes of having the date rather than simply an NSDate.

iPhone SDK - Morning or afternoon

Can someone help me out with something.
I'm trying to get the current part of the day, am or pm. Is there an easy way of accomplishing this?
Thanks.
Sure, use NSDateFormatter:
NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat: #"a"];
NSLog ([formatter stringFromDate: now]);
[formatter release];
Outputs:
2009-08-06 14:20:35.538 yourApp [4971:20b] PM
Maybe there is an easier way .. but this works.
NSDate *now=[NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:NSHourCalendarUnit fromDate:now];
int hour = [components hour];
if ( hour > 12 ){
NSLog(#"PM %d",hour);
} else {
NSLog(#"AM");
}