Time comparison in Cocoa - cocoa

I am storing the date and time in strings using NSUserDefaults when an action is performed. next time the app is run, I want to check the time since the last date and time, and display a message if this is greater than a specified time period.
Is this possible?
In viewDidLoad I retrieve the NSUserDefaults with the saved date and time, and I get the current date, but how do i compare them, and 'do something' if the time difference is bigger than specified?

Use NSDate's timeIntervalSinceDate: method.
By the way, you can store NSDates directly in NSUserDefaults. You don't need to convert them to/from strings.

You could do something like that:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate * lastUpdate = [defaults valueForKey:#"mysettingdate"];
if(!lastUpdate){
lastUpdate = [NSDate dateWithTimeIntervalSince1970:0];
}
NSDate *localDate = [NSDate date];
NSTimeInterval timeZoneOffset = [[NSTimeZone defaultTimeZone] secondsFromGMT];
NSTimeInterval gmtTimeInterval = [localDate timeIntervalSinceReferenceDate] + timeZoneOffset;
NSDate *gmtDate = [NSDate dateWithTimeIntervalSinceReferenceDate:gmtTimeInterval];
NSDateComponents *diff = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:lastUpdate toDate:gmtDate options:0];
NSLog(#"diff in minutes:%d", [diff minute]); //or hour, days, seconds
if ([diff minute]>0) {
//do your stuff :)
}

Related

Xcode preprocessor macro for dates

I want to "hardcode" an expiration date into my beta code. Right now I manually calculate a unix date and compare that to the current date time:
if([[NSDate date] timeIntervalSince1970]>1422748800) mustHalt = TRUE;
I'd like a way of replacing the 1422748800 with a macro that generates the equivalent number for a date 90 days in the future at compile time.
Any suggestions?
The predefined macro __DATE__ is what you need. Here is a SO question related to this. But maybe you want to use a code like this:
const int daysToExpire = 14;
NSString *compileDate = [NSString stringWithUTF8String:__DATE__];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MMM d yyyy"];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
[df setLocale:usLocale];
NSDate *expireDate = [df dateFromString:compileDate];
bool isExpired = ([[NSDate date] compare:expireDate] == NSOrderedDescending); // decide for it

How to calculate and display 4 other days from the day i add in date picker and set local notification to it?

In my App, When i select a day in the datepicker it should automatically calculate and display 4 other days and also it should notify on the corresponding days. For Eg. if i enter 19-08-2014, it should calculate and display the 3rd day, the 7th day, the 14th day and the 21st day from 19-08-2014(the day i entered in datepicker).
How would i achieve this. Any help would be greatly appreciated.
I have added my current code for your reference. This doesnt serve my purpose.
Kindly Help.
(IBAction)save:(UIButton *)sender {
NSDate *pickerDate = [self.picker date];
UILocalNotification *localNotif = [[UILocalNotification alloc]init];
//localNotif.alertBody = _enterText.text;
localNotif.alertBody = #"Please Take Your Rabipur Dosage";
localNotif.fireDate = pickerDate;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.soundName = (UILocalNotificationDefaultSoundName);
localNotif.applicationIconBadgeNumber = 1;
//localNotif.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication]scheduleLocalNotification:localNotif];
[self dismissViewControllerAnimated:YES completion:nil];
}
Create an NSDateComponents object with the date difference you want to add, and add it to pickerDate via NSCalendar -dateByAddingComponents:toDate:options. Then create your notification based on the resulting date.
In this case, something like this:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:3];
NSDate *reminderDate = [gregorian dateByAddingComponents:offsetComponents toDate:pickerDate options:0];
Repeat for 7th, 14th, and 21st day.

UIPickerView Changing UIButton Title Size

So I'm making Alarm Clock to test my skills but can't seem to figure this out... What I've got a UIPickerView that gives a user a time that they can select. Once the time is selected the titleLabel on a UIButton is supposed to update with the time they selected and it does, but it shrinks the new time so it's unreadable... Is there something that needs adjusted with the formatting?
Before when my page loads
Here's my code
- (NSDate *)dateFromString:(NSString *)string {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm"];
NSDate *date = [[NSDate alloc] init];
date = [formatter dateFromString:#"15:00"];
assert(date != nil); // Error converting string to date
return date;
}
After when a user has set a time
Any reason why it might be doing this?
You're experiencing middle truncation of the button's text, and there are a couple of cures for this. You can either make the button bigger by simply adjusting its frame. Or, you can adjust the text size of the title label:
[myButton.titleLabel setFont:[UIFont fontWithName:myButton.titleLabel.font.fontName size:10.0f]];
Actually this seemed to resolve the issue.
alarmButton.titleLabel.adjustsFontSizeToFitWidth = YES;

Calculate time difference in Cocoa

I have got two timevalues in the format: %H%M%S (E.G.161500)
These values are text-based integers.
Is there a simple function in Cocoa that calculates the difference between these two integers using a 60 seconds and minutes scale?
So if
time 1 = 161500
time 2 = 171500
timedifference = 003000
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HHmmss"];
NSDate *date1 = [dateFormatter dateFromString:#"161500"];
NSDate *date2 = [dateFormatter dateFromString:#"171500"];
NSTimeInterval diff = [date2 timeIntervalSinceDate:date1]; // diff = 3600.0
The class for manipulating dates is NSDate. The method for getting time intervals is -timeIntervalSinceDate:. The result is a NSTimeInterval value, which is a double representing the interval in seconds.
You can create a NSDate object from a NSString with +dateWithString:, provided that your date is formatted as 2001-03-24 10:45:32 +0600.
try this code.
- (NSTimeInterval)intervalBetweenDate:(NSDate *)dt1 andDate:(NSDate *)dt2 {
NSTimeInterval interval = [dt2 timeIntervalSinceDate:dt1];
NSLog(#"%f",interval);
return interval;
}
I would create an NSFormatter subclass to parse time values in that format from input data (you can put one on a text field to automatically convert user input, or use it to parse from a data source in code). Have it return the combined number of seconds as an NSTimeInterval (double representing seconds) wrapped in an NSNumber. From there it's easy to subtract the difference, and display it using the same NSFormatter class you created. In both parsing and displaying values, you're the one responsible to write code converting from seconds to hours:minutes:seconds or whatever format you like. You could also convert these values to an NSDate like mouviciel mentioned, if it makes sense for your application. Just keep in mind you're always going to be storing the time difference from a reference date, usually Jan 1st 1970 (NSDate has methods to do this for you).

Is there a better way to find midnight tomorrow?

Is there a better way to do this?
-(NSDate *)getMidnightTommorow {
NSCalendarDate *now = [NSCalendarDate date];
NSCalendarDate *tomorrow = [now dateByAddingYears:0 months:0 days:1 hours:0 minutes:0 seconds:0];
return [NSCalendarDate dateWithYear:[tomorrow yearOfCommonEra]
month:[tomorrow monthOfYear]
day:[tomorrow dayOfMonth]
hour:0
minute:0
second:0
timeZone:[tomorrow timeZone]];
}
Note that I always want the next midnight, even if it happens to be midnight when I make that call, however if it happens to be 23:59:59, I of course want the midnight that is coming in one second.
The natural language functions seem flaky, and I'm not sure what Cocoa would do if I pass 32 in the "day" field. (If that'd work I could drop the [now dateByAddingYears:...] call)
From the documentation:
Use of NSCalendarDate strongly
discouraged. It is not deprecated yet,
however it may be in the next major OS
release after Mac OS X v10.5. For
calendrical calculations, you should
use suitable combinations of
NSCalendar, NSDate, and
NSDateComponents, as described in
Calendars in Dates and Times
Programming Topics for Cocoa.
Following that advice:
NSDate *today = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];
[components release];
NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
components = [gregorian components:unitFlags fromDate:tomorrow];
components.hour = 0;
components.minute = 0;
NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];
[gregorian release];
[components release];
(I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.)
Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it.
Nope - it'll be the same way you use to find midnight today.
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:(24 * 60 * 60)];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit |
NSMonthCalendarUnit |
NSDayCalendarUnit)
fromDate:tomorrow];
NSDate *midnight = [gregorian dateFromComponents:components];
[NSDate dateWithNaturalLanguageString:#"midnight tomorrow"];
Convert your current date and time to a Unix date (seconds since 1970) or DOS style (since 1980), then add 24 hours and convert it back. Then reset the hours, minutes and seconds to zero to get to midnight.
You could try this way:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];
NSDate *tomorrow = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; //it gives us tomorrow with current time
NSDate *midnight = [calendar startOfDayForDate:tomorrow]; //here we get next midnight
It is also easy to retrieve the seconds interval if needed to set up an NSTimer:
double intervalToMidnight = midnight.timeIntervalSinceNow;

Resources