How to compare time greater than 3 sec in ios - ios

How to compare time is greater than 3 sec in ios.
Time is like "2016-05-10 05:31:14". I got code for comparing like greater or less with specific time but how i will achieve it is greater than 3 sec etc.

You can get seconds difference between two dates by
NSDate *someDate;//Some Date
NSLog(#"Seconds --> %f",[[NSDate date] timeIntervalSinceDate: someDate]);

Please try this one. May be Its possible for you:
NSDate* timeNow = [NSDate date];
// If less than 30 seconds, do something
if ([timeNow timeIntervalSinceDate:anEarlierTime] < 30.0f)
{
// Do something
}

- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
// secondsBetweenDates is your seconds difference
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
Here, secondsBetweenDates is your difference in seconds. You can check that it is smaller or greater or equal than 3.
You can get difference here in hours also!
Hope this will help :)

Related

ios8 - seeing if a record is past or future

I'm parsing an array and want to weed out records from before now.
I've got this code:
int i = 0;
for (i=0; i < tempArray.count; i++) {
currentObjectArray = tempArray[i];
NSString *dateString = [currentObjectArray valueForKey:#"ScheduleTime" ];
NSDate *schedule = [dateFormatter dateFromString:dateString];
NSLog(#"schedule: %lu", (unsigned long) schedule );
NSLog(#"now: %lu", (unsigned long)[NSDate date] );
NSTimeInterval distanceBetweenDates = [schedule timeIntervalSinceDate: schedule];
NSLog(#"distanceBetweenDates: %lu", (unsigned long)distanceBetweenDates );
result:
schedule: 16436914033316069376
now: 6174145184
distanceBetweenDates: 0
but the two resulting numbers are incorrect, thus the result is incorrect. Could someone please tell me what I'm doing wrong? Thanks
UPDATE: Thanks to answers below, I've updated my code as follows:
NSString *dateString = [currentObjectArray valueForKey:#"ScheduleTime" ];
NSDate *schedule = [dateFormatter dateFromString:dateString];
float s = [schedule timeIntervalSince1970];
NSLog(#" %f", s );
NSTimeInterval timeInterval = [currentObjectArray timeIntervalSinceNow];
if (timeInterval > 0) {
NSLog(#"YES");
} else {
NSLog(#"NO");
The schedule date format is: "YYYY-MM-DD'T'HH:mm:ss"
Update2: I forgot to add in the local time zone. Thanks for all the help.
These two lines don't do what you think they do.
NSLog(#"schedule: %lu", (unsigned long) schedule );
NSLog(#"now: %lu", (unsigned long)[NSDate date] );
Performing this type cast is asking the system to return you an unsigned long representation of the pointer to the object, which is a memory address and not at all related to time. It is likely that you actually wanted to ask for the NSTimeInterval values.
NSLog(#"schedule: %f", [schedule timeIntervalSince1970] );
NSLog(#"now: %f", [[NSDate date] timeIntervalSince1970] );
Compounding your confusion, you have also misunderstood this line:
NSTimeInterval distanceBetweenDates = [schedule timeIntervalSinceDate: schedule];
You are asking the system to tell you how many seconds are between schedule and schedule; which is obviously always going to be 0 since they are identical. Instead, you probably meant one of:
NSTimeInterval distanceBetweenDates1 = [[NSDate date] timeIntervalSinceDate:schedule];
NSTimeInterval distanceBetweenDates2 = [schedule timeIntervalSinceDate:[NSDate date]];
You only need to check if the time interval is negative or positive to determine if a time comes before or after, respectively.
- (BOOL)isDateInPast:(NSDate *)date {
NSTimeInterval timeInterval = [date timeIntervalSinceNow];
if (timeInterval < 0) {
return YES;
} else {
return NO;
}
}
Note that this doesn't check the condition where the time interval is 0 (the present).
EDIT: Adding to this for further clarification. Your loop code could look something like this...
NSMutableArray *datesOnlyInFuture = [NSMutableArray array];
for (NSDate *date in dateArray) {
if (![self isDateInPast:date]) {
[datesOnlyInFuture addObject:date];
}
}
NSLog(#"Future only dates: %#", datesOnlyInFuture);
This will actually create a new array for you. Clearly plenty of optimizations should be made. For example timeIntervalSinceNow is going to be different each time it is called, so you could pass in a constant date that is set before the loop starts so you're always checking against the same date/time.

How to Create a count up timer in iOS

I have this code:
NSDate *now = [NSDate date];
static NSDateFormatter *dateFormatter;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = #"h:mm:ss";
}
recordStatusLabel.text = [dateFormatter stringFromDate:now];
NSLog(#"Time now: %#", [dateFormatter stringFromDate:now]);
that counts the current time. How can i change it to start in this format?
00:00:00 (hours:minutes:seconds)
from a NSString variable:
Example: i got this value for my variable
NSString * time = #"02:16:23";
then the counter will continue the count to:
02:16:24
.
.
.
02:20:13
Create an instance of NSTimer class and set time for event fire 1 second with repeat option YES. In the event handling update your label with current time. When your functionality is complete, invalidate the timer to stop firing events.
Here is the code to create instance of NSTimer class:
NSTimer *countUpTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:#selector(countUpTimerFired:) userInfo:nil repeats:YES];
Here is the method for event handling:
- (void)countUpTimerFired:(id)sender {
dispatch_async(dispatch_get_main_queue(), ^{
recordStatusLabel.text = [dateFormatter stringFromDate:[NSDate date]];
});
}
Keep of dateFormatter and countUpTimer as class variables.
This is the simple approach to achieve your required functionality as you are starting your time from current device time; So you won't be requiring extra efforts to get value from label, incrementing the value and then converting back to string.
EDIT:
If you want to start the counter from anyother time value or from a string, you can keep a integer variable to keep the value of time in seconds. Then increment the value when timer event gets called (every second) and then converting that integer to time string.
Here's the code for initial value:
NSString *timeString = recordStatusLabel.text; //contains a string in time format like #"2:16:23" or #"00:00:00" or current time or any other value.
NSArray *timeComponents = [timeString componentsSeparatedByString:#":"];
int timeInSeconds = [timeComponents[0] intValue]*3600 + [timeComponents[1] intValue]*60 + [timeComponents[2] intValue];
in the event handling of timer:
- (void)countUpTimerFired:(id)sender {
timeInSeconds++;
int hours = timeInSeconds/3600;
int minutes = (timeInSeconds%3600)/60;
int seconds = timeInSeconds%60;
dispatch_async(dispatch_get_main_queue(), ^{
[recordStatusLabel setText:[NSString stringWithFormat:#"%d:%02d:%02d", hours, minutes, seconds]];
});
}
Since you are dealing with a timer which the fastest value is the second, then to achieve performance you just fire a timer which repeats every second.
Declare your instance variables
#implementation Yourclass {
NSDate *startDate;
NSTimer *yourTimer;
NSString *myTime;
}
When you click a button to start timer
-(IBAction)startTimer:(id)sender {
startDate = [NSDate date];
yourTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(timeHandler:) userInfo:nil repeats:YES];
[yourTimer fire];
}
Implement your method which is the handler method of timer
-(void)timeHandler:(NSTimer *)myTimer {
//Difference between dates in seconds
NSTimeInterval elapsedTime = [startDate timeIntervalSinceNow];
//Divide by 3600 to get the hours
NSInteger hours = elapsedTime/3600;
//Divide by 60 to get the minutes
NSInteger minutes = elapsedTime/60;
NSInteger seconds = elapsedTime;
myTime = [NSString stringWithFormat:#"%i:%i:%i",hours, minutes, seconds];
// update the label
recordStatusLabel.text = myTime;
}

How to find a time is one hour before and within my custom time in iOS

I need to start download exactly one hour before or within my custom time.
For example I should start to download at 7 AM or with 8 AM (8 AM is my custom time). How I can achieve this. the following is my code,
AppDelegate * iDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
iDelegate.mStartTime = [[NSUserDefaults standardUserDefaults] objectForKey:START_TIME];
int stHr = [[[iDelegate.mStartTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int stMin = [[[iDelegate.mStartTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
NSDate *today = [[[NSDate alloc] init]autorelease];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
NSDateComponents *offsetComponents = [[[NSDateComponents alloc] init]autorelease];
[offsetComponents setHour:+1];
NSDate *modifiedDate = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
NSDateComponents * timecomponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:modifiedDate];
NSInteger currentHour = [timecomponents hour];
NSInteger currtMin = [timecomponents minute];
int nowTime = (currentHour*60)+currtMin;
if (nowTime <= formStTime || nowTime >= formStTime)
{
// start download
}
But I should not download if the current time is 8 AM or after 8 AM .
What is the mistake in my code ? Please suggest. Thanks.
I have not considered in detail all your code's logic, but this struck to me:
if (nowTime <= formStTime || nowTime >= formStTime)
this condition will be always true. This explains why your code is not working as you wish since it should always do the downloading, even after 8AM. You are after a condition link this:
if (nowTime >= minimumTime || nowTime < maximumTime)
However, I have not clear from your question how you define minimum and maximumTime so cannot advise further. If formStTime is your minimumTime and we assume that maximumTime is just one hour later, you could have:
if (nowTime >= formStTime || nowTime < formStTime + 60)
(If I read correctly your code.)
EDIT: after your clarification in the comments, the condition to start the download would be:
if (nowTime < formStTime)
//-- start download
To handle the second part of your requirements (stopping the download at the given maximum time) you will need a different logic altogether. One way of doing it would be starting a NSTimer when you start a download that will fire at the right time; then, you would check if the download is still going on and stop it. A NSTimer is just one of multiple possibilities you have (you could also use displatch_after), but the basic idea will not change.
E.g.:
if (nowTime < formStTime) {
//--= start download
self.timer = [NSTimer scheduledTimerWithTimeInterval:(formStTime - nowTime)*60 //-- seconds
target:self
selector:#selector(timeExpired:)
userInfo:nil
repeats:NO];
}
then in the handler function:
- (void)timeExpired:(NSTimer*)timer {
if (downloadStillOngoing)
//-- stop the download
}
When your download is done, you should call [self.timer invalidate], also.
However, you will need to fill a number of gaps in my sketch implementation to get to a working solution. If you need more help about stopping the download, you will need to provide more information about how you are doing the download and possibly ask a new question.
Modify your if condition with below code:
if (nowTime >= formStTime && nowTime <= formStTime + 60)

iOS - Friendly NSDate format

I need to display the date of posts in my app to the user, right now I do it in this format: "Fri, 25 May". How would I format an NSDate to read something like "2 hours ago"? To make it more user friendly.
Take a look at FormaterKit https://github.com/mattt/FormatterKit
Created by mattt who also created AFNetworking.
NSDateFormatter can't do things like that; you're going to need to establish your own rules. I guess something like:
- (NSString *)formattedDate:(NSDate *)date
{
NSTimeInterval timeSinceDate = [[NSDate date] timeIntervalSinceDate:date];
// print up to 24 hours as a relative offset
if(timeSinceDate < 24.0 * 60.0 * 60.0)
{
NSUInteger hoursSinceDate = (NSUInteger)(timeSinceDate / (60.0 * 60.0));
switch(hoursSinceDate)
{
default: return [NSString stringWithFormat:#"%d hours ago", hoursSinceDate];
case 1: return #"1 hour ago";
case 0:
NSUInteger minutesSinceDate = (NSUInteger)(timeSinceDate / 60.0);
/* etc, etc */
break;
}
}
else
{
/* normal NSDateFormatter stuff here */
}
}
So that's to print 'x minutes ago' or 'x hours ago' up to 24 hours from the date, which will usually be one day.
I wanted a date format like Facebook does for their mobile apps so I whipped up this NSDate category - hope it is useful for someone (this kind of stuff should really be in a standard library!) :)
https://github.com/nikilster/NSDate-Time-Ago
There's also SEHumanizedTimeDiff which does/is about to support multiple languages if that's an issue for you:
https://github.com/sarperdag/SEHumanizedTimeDiff
There are about a million ways you could do this, but here's a quick one:
NSString* hoursAgo = [NSString stringWithFormat:#"%.0lf hours ago", fabs([date timeIntervalSinceNow] / 3600.0)]
Of course, this doesn't check that date is actually from the past, doesn't do anything but hours, etc. But, you probably get the idea.
timeIntervalSinceNow returns how many seconds have passed since a given date, with positive numbers being a date in the future and negative numbers being a date in the past. So, we get how many seconds have passed, divide it by 3600 seconds in an hour to compute the hours that have passed, and then put its absolute value into the string "n hours ago".
Here is a pretty good answer this will take in seconds since the epoch(Jan 1, 1970) and return you a nice formatted string like '3 minutes ago'. Simply call it with your date object like so:
[timeAgoFromUnixTime:[myDateObject timeIntervalSince1970]];
+ (NSString *)timeAgoFromUnixTime:(double)seconds
{
double difference = [[NSDate date] timeIntervalSince1970] - seconds;
NSMutableArray *periods = [NSMutableArray arrayWithObjects:#"second", #"minute", #"hour", #"day", #"week", #"month", #"year", #"decade", nil];
NSArray *lengths = [NSArray arrayWithObjects:#60, #60, #24, #7, #4.35, #12, #10, nil];
int j = 0;
for(j=0; difference >= [[lengths objectAtIndex:j] doubleValue]; j++)
{
difference /= [[lengths objectAtIndex:j] doubleValue];
}
difference = roundl(difference);
if(difference != 1)
{
[periods insertObject:[[periods objectAtIndex:j] stringByAppendingString:#"s"] atIndex:j];
}
return [NSString stringWithFormat:#"%li %#%#", (long)difference, [periods objectAtIndex:j], #" ago"];
}
In newer versions of iOS since this question was asked, NSDateFormatter has had this ability added. It can now do it using the doesRelativeDateFormatting property.
+(NSString*)HourCalculation:(NSString*)PostDate
{
NSLog(#"postdate=%#",PostDate);
// PostDate=#"2014-04-02 01:31:04";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
[dateFormat setTimeZone:gmt];
NSDate *ExpDate = [dateFormat dateFromString:PostDate];
NSLog(#"expdate=%#",ExpDate);
NSLog(#"expdate=%#",[NSDate date ]);
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit|NSWeekCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:ExpDate toDate:[NSDate date] options:0];
// NSLog(#"year=%d",components.year);
//
// NSLog(#"month=%d",components.month);
//
// NSLog(#"week=%d",components.week);
//
// NSLog(#"day=%d",components.day);
//
// NSLog(#"hour=%d",components.hour);
//
// NSLog(#"min=%d",components.minute);
//
// NSLog(#"sce=%d",components.second);
//
NSString *time;
if(components.year!=0)
{
if(components.year==1)
{
time=[NSString stringWithFormat:#"%ld year",(long)components.year];
}
else{
time=[NSString stringWithFormat:#"%ld years",(long)components.year];
}
}
else if(components.month!=0)
{
if(components.month==1)
{
time=[NSString stringWithFormat:#"%ld month",(long)components.month];
}
else{
time=[NSString stringWithFormat:#"%ld months",(long)components.month];
}
// NSLog(#"%#",time);
}
else if(components.week!=0)
{
if(components.week==1)
{
time=[NSString stringWithFormat:#"%ld week",(long)components.week];
}
else{
time=[NSString stringWithFormat:#"%ld weeks",(long)components.week];
}
// NSLog(#"%#",time);
}
else if(components.day!=0)
{
if(components.day==1)
{
time=[NSString stringWithFormat:#"%ld day",(long)components.day];
}
else{
time=[NSString stringWithFormat:#"%ld days",(long)components.day];
}
}
else if(components.hour!=0)
{
if(components.hour==1)
{
time=[NSString stringWithFormat:#"%ld hour",(long)components.hour];
}
else{
time=[NSString stringWithFormat:#"%ld hours",(long)components.hour];
}
}
else if(components.minute!=0)
{
if(components.minute==1)
{
time=[NSString stringWithFormat:#"%ld min",(long)components.minute];
}
else{
time=[NSString stringWithFormat:#"%ld mins",(long)components.minute];
}
// NSLog(#"time=%#",time);
}
else if(components.second>=0){
// NSLog(#"postdate=%#",PostDate);
// NSLog(#"expdate=%#",[NSDate date ]);
if(components.second==0)
{
time=[NSString stringWithFormat:#"1 sec"];
}
else{
time=[NSString stringWithFormat:#"%ld secs",(long)components.second];
}
}
return [NSString stringWithFormat:#"%# ago",time];
}
This code will show you time in
------------sec like 2 sec ago
------------min like 2 mins ago
------------hours like 2 hours ago
------------days like 2 days ago
------------week like 2 weeks ago
------------month like 2 months ago
Lastly....
years like 2 years ago
:) try this
Adding to the solution try this more simplified method
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:passed toDate:[NSDate date] options:0];
NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
if (interval < 60) timestampString = [NSString stringWithFormat:#"%d seconds ago" ,today.second];
else if (interval < 60 * 60) timestampString = [NSString stringWithFormat:#"%d minutes ago" ,today.minute];
else if (interval < 60 * 60 * 24) timestampString = [NSString stringWithFormat:#"%d hours ago" ,today.hour];
else timestampString = [NSString stringWithFormat:#"%d days ago" ,today.day];

Convert a NSDate to milliseconds epoch time

I need to be able to convert a date to a time stamp, an epoch in milliseconds.
All I see online are for converting milliseconds to NSDate and not the other way round. Any help out there?
NSTimeInterval is a double that already contains sub-second data after the decimal point. Depending what you need, your conversion could be a simple as multiplying by 1000.
- (void)testDateFormat
{
NSDate *date = [NSDate date];
NSLog(#"Time: %f", floor([date timeIntervalSince1970] * 1000));
NSLog(#"Time: %f", floor([date timeIntervalSince1970]));
NSLog(#"Time: %lli", [#(floor([date timeIntervalSince1970] * 1000)) longLongValue]);
NSLog(#"Time: %lli", [#(floor([date timeIntervalSince1970])) longLongValue]);
}
// Result
// 2013-04-15 13:28:11.284 TestApp[10469:907] Time: 1366057691284.000000
// 2013-04-15 13:28:11.286 TestApp[10469:907] Time: 1366057691.000000
// 2013-04-15 13:28:11.287 TestApp[10469:907] Time: 1366057691284
// 2013-04-15 13:28:11.288 TestApp[10469:907] Time: 1366057691
timeIntervalSince1970 will return seconds from 1970. There are other timeIntervalSince methods if needed.
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/timeIntervalSince1970
timeIntervalSince1970 multiply the return value by 1000
because the returned value is in second not in millisecond
kindly check that website for more testing http://currentmillis.com/

Resources