Measuring time Interval Since Now - iphone

anyone know or can provide some example code relating to "timeIntervalSinceNow" method...
I need something like... time2(when app eneters foreground) - time1(when app enters background) = time3(the difference in times)... this is so i can use this number(pref in seconds) to calculate the time i have lost while the app has been in background !!
I am having trying trying to create the date objects, receive the object and display/use in a label....

Actually, to answer your original question, myles, you can use timeIntervalSinceNow.
In the statement below, inputDate has been initialized as an NSDate and set to some date (you could just try [NSDate *inputDate = [NSDate date]; to set the date at the current date and time.
NSTimeInterval timeToAlert =[inputDate timeIntervalSinceNow];
The next line is a way to put that NSTimeInterval into a string.
NSMutableString *timeinterval = [NSMutableString string];
[timeinterval appendFormat:#"%f",timeToAlert];
Finally, the app delegate class is typically where code can be written to handle coming in and out of background. Good luck!

timeIntervalSinceNow tells you the offset of an NSDate from the current time. You want timeIntervalSinceDate::
NSDate *appEnteredForeground = ...;
NSDate *appEnteredBackground = ...;
NSTimeInterval difference = [appEnteredBackground timeIntervalSinceDate: appEnteredForeground];

You can calculate the difference between two dates with the timeIntervalSinceDate: method:
//When app enters background:
self.backgroundDate = [NSDate date]; //this should be a property
//...
//When the app comes back to the foreground:
NSTimeInterval timeSpentInBackground = [[NSDate date] timeIntervalSinceDate:self.backgroundDate];
NSTimeInterval is simply a typedef for double, it's measured in seconds. [NSDate date] instantiates an NSDate object with the current date and time.

Related

Inconsistancey between iphone device and simulator when creating NSDate

I'm getting a curious issue when creating NSDates using dateWithTimeIntervalSince1970 on a simulator versus an iPhone device. I am simply translating an ISO8601 timestamp from an NSDate to milliseconds and then back to a NSDate.
NSDateFormatter *iso8601Formatter = [[NSDateFormatter alloc] init];
iso8601Formatter.dateFormat = TSMISO8601FormatString; // "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
NSDate startDate = [iso8601Formatter dateFromString: #"2014-03-19T09:46:00-06:00"];
long startTimeMilliseconds = [startDate timeIntervalSince1970] * 1000;
startDate = [NSDate dateWithTimeIntervalSince1970:(startTimeMilliseconds / 1000)];
When I run this on the simulator, I get the same date back but when I run it on my iPhone, I get back this. I'm really confused as to why I'm getting back a wildly different day
1970-01-25 20:31:23 +0000 // iPhone device results
I have checked to make sure that my timezone, date, and time format are the same on both just to make sure that this isn't the issue. And both are running iOS 7.1. I have also attempted to set both the locale and timezone for the NSDateFormatter without any success.
Any help would be appreciated
This:
long startTimeMilliseconds = [startDate timeIntervalSince1970] * 1000;
Should Be:
double startTimeMilliseconds = [startDate timeIntervalSince1970] * 1000;
Here's why,
The maximum long can be found with LONG_MAX and it will log:
2147483647
Your current time interval is:
1395243960000.000000
Long can't go big enough.

Adding one millisecond to current time objectivec

Is there any way to add one millisecond in to current time in objective c . I will fetch the timestamp from server and want to show with millisecond repeatedly ( I dont want to use the system time) .Any help is appreciated .
Thanks in advance .
Read the timestamp into an NSDate. Than use
+ (id)dateWithTimeInterval:(NSTimeInterval)seconds sinceDate:(NSDate *)date
Should work.
You need to use an object of the NSTimer class.
Some sample code:
-(void)startTimer {
theTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/1000.0 target:self selector:#selector(updateTimer) userInfo:nil repeats:YES];
//the method updateTimer will be called once every millisecond
}
-(void)updateTimer {
//add one millisecond to the global time variable and display it in a label
}
-(void)stopTimer {
[theTimer invalidate]; //pauses the timer
}
Edit
For using a global Time variable, NSDate is probably the right class.
You can init the object using a time interval, for eg. 600 seconds before now:
NSDate *globalDateTime = [[NSDate alloc] initWithTimeIntervalSinceNow:-600];
To add 1 millisecond to the time:
globalDateTime = [globalDateTime dateByAddingTimeInterval:1.0/1000.0];
And to populate your global time variable in a string:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"]; // use yyyy-MM-dd if you need to show the year, month or day
NSString *dateTimeString = [dateFormatter stringFromDate:globalDateTime];
The NSTimeInterval class "yields sub-millisecond precision over a range of 10,000 years."
Refer to apple's documentation on NSDate for more details:

How to set Max date dynamically for date picker in iPhone?

I have date picker and i want to set maximum date as TODAY date which will change daily.
For ex today's date is 28/6/2011 so maximum date is 28/6/2011 but when i use my app tomorrow it will be change to 29/6/2011.
How to set this?
Thanks
Set the maximumDate property in viewWillAppear: method like this,
datePicker.maximumDate = [NSDate date];
To deal with date change while the application is being used, get the time left till tomorrow and set an NSTimer to trigger off at date change and then update the UIDatePicker instance.
NSDate * tomorrow = [NSDate dateWithNaturalLanguageString:#"12 AM tomorrow"];
NSTimeInterval timeInterval = [tomorrow timeIntervalSinceNow];
/* Create an NSTimer to trigger a method to update the datePicker's maximumDate
after timeInterval */
If you look in the documentation you will see that there is a property of UIDatePicker called maximumDate. If you then look at the documentation for NSDate you will see that the class method date returns an NSDate with the current date and time, therefore:
`someDatePicker.maximumDate = [NSDate date];
will set the date picker to not allow any date (or time) later than that moment.
As [NSDate date] or Date() returns the current today's date.
In Objective-C
Set the date picker's minimumDate property:
datePicker.minimumDate = [NSDate date];
In Swift 4.x,
datePicker.minimumDate = Date()
(Where datePicker is a reference to your UIDatePicker )

Comparing a date from the picker to current date

In my date picker i can select a date from the list.
I save it in my string pickUpDateTime
self.pickUpDateTime = [NSString stringWithString:[apiFormat stringFromDate:d]];
I'm having a problem where the user is able to pick a date in the past. Is there some way to get the current day and check that its in the future?
My string holds the date like this 2010-11-04.
The user shouldnt be able to select a day in the past or the current day.
Thanks
-Code
You can get the current date and time with:
NSDate *now = [NSDate date];
Compare the 2 dates with:
if ([d compare:now] == NSOrderedDescending) {
// d is later than now
} else {
// d is earlier than or equal to now
}
If you're using a UIDatePicker, just set
datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:24*3600];
e.g. to allow dates starting tomorrow. Working back from the date string "2010-11-04" to a NSDate object is possible but cumbersome. (but if you insist, have a look at NSDateFormatter)
Lots of answers above give good advice about working with NSDates in general; things are a tiny bit more complicated if you want to round to the start of the day to say e.g. 'at least tomorrow' rather than 'at least 24 hours away'.
In general terms:
get an instance of NSCalendar to represent the Gregorian calendar
use the NSCalendar to convert an NSDate into an NSDateComponents representing just the day, month and year
use the NSCalendar to convert the NSDateComponents back into an NSDate
use arithmetic as recommended elsewhere to increment the NSDate a day into the future, for example
I have to dash, but relevant methods are:
NSCalendar +currentCalendar or -initWithCalendarIdentifier:NSGregorianCalendar to be extra safe
NSCalendar -components:fromDate: (the first parameter is a flag field indicating which bits of the date you need to be filled in) and -dateFromComponents:
NSDate -timeIntervalSinceDate:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
NSString *tempStr=[NSString stringWithFormat:#"%#",[df stringFromDate:datePicker.date]];
txtBirth.text=tempStr;
NSString *birthDate = tempStr;
NSDate *todayDate = [NSDate date];
int time = [todayDate timeIntervalSinceDate:[df dateFromString:birthDate]];
int numberOfDays = time/86400;
hear number of data return data difference.....

How to tell amount of hours since NSDate

I initiated an NSDate with [NSDate date]; and I want to check whether or not it's been 5 hours since that NSDate variable. How would I go about doing that? What I have in my code is
requestTime = [[NSDate alloc] init];
requestTime = [NSDate date];
In a later method I want to check whether or not it's been 12 hours since requestTime. Please help! Thanks in advance.
NSInteger hours = [[[NSCalendar currentCalendar] components:NSHourCalendarUnit fromDate:requestTime toDate:[NSDate date] options:0] hour];
if(hours >= 5)
// hooray!
int seconds = -(int)[requestTime timeIntervalSinceNow];
int hours = seconds/3600;
Basically here I'm asking how many seconds have passed since we first got our requestTime. Then with a little math magic, aka dividing by the number of seconds in an hour, we can get the number of hours that have passed.
A word of caution. Make sure you use the "retain" keyword when setting the requesttime. xcode likes to forget what NSDate objects are set to without it.
requestTime = [[NSDate date] retain];
Try using this method, or something along these lines.
- (int)hoursSinceDate :(NSDate *)date
{
#define NUBMER_OF_SECONDS_IN_ONE_HOUR 3600
NSDate *currentTime = [NSDate date];
double secondsSinceDate = [currentTime timeIntervalSinceDate:date];
return (int)secondsSinceDate / NUBMER_OF_SECONDS_IN_ONE_HOUR;
}
You can then do a simple check on the integer hour response.
int hours = [dateUtilityClass hoursSinceDate:dateInQuestion];
if(hours < 5){
# It has not yet been 5 hours.
}