iPhone SDK - Morning or afternoon - iphone

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");
}

Related

How can I make an NSDate aim for the closest future match?

Here's an example of what I want. The user may set up an alarm in my app for 1 minute in the future, so they can test it out. The time might be 19:23, so they'll set the alarm to 19:24, in which case I want it to be triggered on the next occurrence of 19:24 - in 1 minute's time.
If they set the alarm for 8am, I don't want it to set to 8am on the current day, but on the next occurrence of 8am - on following day.
How can I get it to aim for the next occurrence of the time chosen?
Assuming that the alarm time is given as "hour" and "minute", the following code
should produce the desired result:
NSDate *now = [NSDate date];
// Example values for testing:
NSUInteger alarmHour = 10;
NSUInteger alarmMinute = 5;
// Compute alarm time by replacing hour/minute of the current time
// with the given values:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:now];
[comp setHour:alarmHour];
[comp setMinute:alarmMinute];
NSDate *alarm = [cal dateFromComponents:comp];
// If alarm <= now ...
if ([alarm compare:now] != NSOrderedDescending) {
// ... add one day:
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:1];
alarm = [cal dateByAddingComponents:oneDay toDate:alarm options:0];
}
More tersely, what #HotLicks suggests:
NSDate *userEnteredDate;
NSDate *now = [NSDate date];
if (now == [now laterDate:userEnteredDate]) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:255 fromDate:userEnteredDate]; // 255= the important component masks or'd together
components.day += 1;
userEnteredDate = [[NSCalendar currentCalendar] dateFromComponents:components];
}
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
NSDateFormatter *formatter_ = [[NSDateFormatter alloc]init];
NSDate *alarmDate = [formatter dateFromString:#"enter your users alarm time-examle(2345)"];
NSDate *currentDate = [NSDate date];
[formatter setDateFormat:#"HHmm"];
NSDate *finalDate;
if ([[formatter stringFromDate:currentDate] intValue] > [[formatter stringFromDate:alarmDate] intValue]) {
[formatter setDateFormat:#"HH:mm"];
[formatter_ setDateFormat:#"dd MM yyyy"];
NSDate *date = [currentDate dateByAddingTimeInterval:60*60*24*1];
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:date]]];
}else{
finalDate = [formatter_ dateFromString:[NSString stringWithFormat:#"%# %#",[formatter stringFromDate:alarmDate],[formatter_ stringFromDate:currentDate]]];
}

Difference in hours between two NSDate

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

writing logic Date difference - Newbie

Is there a way to subtract the current date by 5. say if today is 2008-12-9 i need to get the date 5 days back. If we output this, the date should display as 2008-12-4.
How can i code this programatically? or a tutorial that would help
Always use NSCalendar and NSDateComponents for date calculations. This will take into account oddities like leap years with 29 days in February, leap seconds and daylight saving changes.
NSDate *date = [NSDate date]; // Using current date here
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = - 5; // Find date for 5 days ago
NSDate *newDate = [calendar dateByAddingComponents:components toDate:date options:0];
Use NSDateComponents
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init] autorelease];
[offsetComponents setDays:-5];
NSDate *fiveDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
to convert it to a string with the preferred format, use NSDateFormatter
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *formattedDateString = [dateFormatter stringFromDate:fiveDaysAgo];
This is the brute-force way:
Sustract 5 from DAY.
If DAY < 0, add number of days of the previous month and sustract 1 from MONTH.
If MONTH < 0, add number of month of a year and sustract 1 from YEAR.
The advantage of the brute-force approach is that it will work with every language.
#define SOME_HOUR -24*5
NSDate *today = [NSDate date];
NSDate *someDay = [NSDate dateWithTimeInterval:60*60*SOME_HOUR sinceDate:today];

How to get full timestamp with only passing hours and minutes with NSDateFormatter?

I think this is just a minor problem. After searching for some time I still can't figure it out. Hopefully you can. :-)
I want to get a full timestamp of today, passing own hours and minutes.
My approach was the following(dateStr is #"11:30" for example):
NSDateFormatter *myFormatter = [[[NSDateFormatter alloc] init] autorelease];
[myFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[myFormatter setDateFormat:#"HH:mm"];
NSDate *tmpDate = [myFormatter dateFromString:dateStr];
[myFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss ZZZ"];
...???
So now I get
1970-01-01 11:30:00 +0000
What do I habe to do to apply the dateStyle to my NSDate and get the correct date of today?
I know that I can use [NSDate date] to get the actual date but what can I do to "manipulate" only minutes and hours?
Would be great to get some help from you guys :)
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:[NSDate date]];
[components setHour:hour];
[components setMinute:minute];
NSDate *date = [gregorian dateFromComponents:components];
[gregorian release];

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.