iOS difference between 2 times - iphone

This is the situation here. I have current time in epoch. also I have number of days. I want to find the difference between the 2 to give some past time in epoch format. i.e.
currentEpochTime - (x days) to give some past time in epoch format.
This is what I have gotten so far -
+ (double)currTimeInEpoch
{
NSDate *todayDate = [NSDate date];
double ti = [todayDate timeIntervalSince1970]*1000;
return ti;
}
+ (NSString *)timeDiff:(double)epoch diff:(double)diffInDays
{
double past = epoch - (diffInDays * 24 * 60 * 60 * 1000);
return [[NSNumber numberWithDouble:past] stringValue];
}
Is what I am doing correct? Not sure about it. Is there any simpler way to do this ?

It's dangerous to go alone. Take this.
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = -40; // Number of days to subtract
NSDate *newDate = [[NSCalendar autoupdatingCurrentCalendar] dateByAddingComponents:dateComponents toDate:[NSDate date] options:0];
NSTimeInterval newDateInEpochTime = [newDate timeIntervalSince1970] * 1000;

Related

How i can take the differece between two timings in iphone?

I have an application in which i need to show a label in the tableview as Xseconds ago and xminutes&yseconds ago,X hrs ago like that.i am doing like this `
NSString *todaysdateString=[dict objectForKey:#"sendingtime"];
NSString *time = todaysdateString;
NSString*todaysdateString1=[NSString stringWithString: #" "];
NSDate *date1;
NSDate *date2;
//{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"HH:mm:ss"];
date1 = [formatter dateFromString:time];
date2 = [formatter dateFromString:[formatter stringFromDate:[NSDate date]]];
[formatter release];
//}
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];
float seconds = interval;
float hour = interval / 3600;
float minute =(interval - hour*3600) / 60;
NSLog(#"%02.0f,%02.0f,%02.0f",hour, minute, seconds);
`But this wont giving me the desired answers,I am getting like -0,00,-297 that is utterly wrong.Can anybody point me in where i am going wrong..
Use a NSCalendar to do this, maybe this code helps you
NSCalendar *c = [NSCalendar currentCalendar];
NSDateComponents *components = [c components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit
fromDate:initialDate
toDate:endDate
options:0];
and in the components variables you will have the differences, get it back using: components.day, components.minute and components.second
As your seconds is in negative, you should swap your date here
NSTimeInterval interval = [date1 timeIntervalSinceDate: date2];
to :
NSTimeInterval interval = [date2 timeIntervalSinceDate: date1];
And can do as :
NSInteger intervalInt=interval;
NSInteger seconds = intervalInt % 60;
NSInteger minutes = (intervalInt / 60) % 60;
NSInteger hours = intervalInt / (60 * 60);
NSString *result = [NSString stringWithFormat:#"%02ld:%02ld:%02ld", hours, minutes, seconds];

How to find particular day of a month?

I've done a lot of study on NSDate NSDateFormatter and NSCalendar but cannot figure out a way to find a particular day of a month.
For example,
I want to find the date of 2nd Monday of December (10/12/2012). I know how to find number of week or number of month but cannot figure out the way to do it.
Thanks.
// Set start date of the month you want
NSString *str = #"01 - 12 - 2012";
NSDateFormatter *formatter1 = [[[NSDateFormatter alloc] init] autorelease];
[formatter1 setDateFormat:#"dd - MM - yyyy"];
NSDate *date = [formatter1 dateFromString:str];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *weekdayComponents = [gregorian components:(NSDayCalendarUnit | NSWeekdayCalendarUnit) fromDate:date];
// Get the weekday with sunday as one
NSInteger weekday = [weekdayComponents weekday];
int weekNumber = 2;
int dayOfweek = 2;
int x = (7 - weekday) * (weekNumber - 1) + dayOfweek;
// Add the no. of weeks - 1 or - 2 depending on the value of x.
// Also Add 1 as the start date is 1st Dec.
if(x < 7)
{
x += 7 * (weekNumber - 1) + 1;
}
else
{
x += 7 * (weekNumber - 2) + 1;
}
Try to find the particular day of the week from these codes then apply it for the month as well :)
Please refer to the following links :-
How do I get the day of the week with Cocoa Touch?
Number of days in the current month using iPhone SDK?
Hope They Help :)
Robin's and Gill's answers helped me get a solution to my problem. With some more editing I was able to get a solution to my problem.
Here is the code that I used to get the solution
-(void)findWeekDay:(NSInteger)weekDay forWeek:(NSInteger)week OfMonth:(NSInteger)month OfYear:(NSInteger)year
{
NSDateComponents *dateComp = [[NSDateComponents alloc]init];
[dateComp setYear:year];
[dateComp setMonth:month];
[dateComp setDay:1];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *firstDate=[gregorian dateFromComponents:dateComp]; //Sets first date of month.
firstDate=[self dateToGMT:firstDate];
NSLog(#"First date: %#",firstDate);
NSDateComponents *dateComp1 = [gregorian components:NSDayCalendarUnit|NSWeekdayCalendarUnit fromDate:firstDate];
NSInteger firstWeekDay=[dateComp1 weekday]; //Gets firstday of a week. 1-Sunday, 2-Monday and so on.
NSLog(#"First Week Day: %d",firstWeekDay);
NSRange daysInMonth = [gregorian rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:firstDate]; //To get number of days in that month
NSInteger x; //days to be added to first date
if (firstWeekDay < weekDay) {
x = (weekDay - firstWeekDay) + (7 * (week-1));
}
if (firstWeekDay > weekDay) {
x = (7 - firstWeekDay + weekDay) + (7 * (week-1));
}
if (firstWeekDay == weekDay) {
x = (7 * (week-1));
}
if (x > daysInMonth.length) {
NSLog(#"Invalid Date: %d",x);
}
else {
NSLog(#"Days to be added: %d",x);
NSDateComponents *dateComp2 = [[NSDateComponents alloc]init];
[dateComp2 setYear:0];
[dateComp2 setMonth:0];
[dateComp2 setDay:x];
NSDate *desiredDate = [gregorian dateByAddingComponents:dateComp2 toDate:firstDate options:0];
NSLog(#"Your desired date is: %#",desiredDate);
}
}
- (NSDate *)dateToGMT:(NSDate *)sourceDate {
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:destinationGMTOffset sinceDate:sourceDate];
return destinationDate;
}
Now to find 3rd Monday of December 2012 call the method as
[self findWeekDay:2 forWeek:3 OfMonth:12 OfYear:2012];

how to compare time with current date and time?

In My application I have to complete a particular task in given time.So first i calculated the time complete the task in seconds and then add that time to the current that like this.
NSDate *mydate = [NSDate date];
NSTimeInterval TotalDuraionInSec = sec.cal_time * 60;
TaskCmpltTime = [mydate addTimeInterval:TotalDuraionInSec];
NSLog(#"task will be completed at%#",TaskCmpltTime);
now I compare time like this
if([CurrentTime isEqualToDate:AfterCmpltTime]){
NSLog (#"Time Finish");
}
but I want to know is Time is left or not.Is current time is less then or greater then current time how can i know this ?
timeIntervalSinceNow compares the NSDate with Now. if NSDate is after Now the return value is possitive, if the date is earlier than Now the result is negative.
double timeLeft = [TaskCompltTime timeIntervalSinceNow];
if( timeLeft > 0.0 )
// still time left
else
//time is up
I have an example where I get the time from a picker and check if its today or tomorrow. You should be able to just take the code and use it in your way...
int selectedHour = [customPickerView selectedRowInComponent:0];
int selectedMinute = [customPickerView selectedRowInComponent:1];
NSDate *today = [NSDate date];
NSDateFormatter *weekdayFormatter = [[[NSDateFormatter alloc] init]autorelease];
NSDateFormatter *hmformatter = [[[NSDateFormatter alloc] init]autorelease];
[hmformatter setDateFormat: #"hh mm"];
[weekdayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[weekdayFormatter setDateFormat: #"EE"];
// NSString *formattedDate = [formatter stringFromDate: today];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
NSDateComponents *dateComponentsToday = [gregorian components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit) fromDate:today];
NSInteger currentHour = [dateComponentsToday hour];
NSInteger currentMinute = [dateComponentsToday minute];
NSString *weekday;
if ((selectedHour > currentHour) | ((selectedHour == currentHour) & (selectedMinute > currentMinute))) {
//so we are still in today
weekday = [weekdayFormatter stringFromDate: today];
weekday = NSLocalizedString(#"today", #"today");
} else {
//the timer should start tomorrow
NSTimeInterval secondsPerDay = 24 * 60 * 60;
NSDate *tomorrow = [today dateByAddingTimeInterval:secondsPerDay];
weekday = [weekdayFormatter stringFromDate: tomorrow];
weekday = NSLocalizedString(#"tomorrow", #"tomorrow");
}
Yeah, for your purposes it's probably best to work in time intervals. The NSTimeInterval in Objective-C is an alias for double, and it represents a time value in seconds (and, of course, fractions, down to at least millisecond resolution).
There are several methods on NSDate for this -- +timeIntervalSinceReferenceDate, which returns the number of seconds since Jan 1, 2001, -timeIntervalSinceReferenceDate, which returns the difference in time between the supplied NSDate object and Jan 1, 2001, -timeIntervalSinceDate:, which returns the difference in seconds between the two NSDate objects, and -timeIntervalSinceNow, which returns the difference between the current time and the NSDate object.
Lots of times it's most convenient to store an NSDate value as an NSTimeInterval instead (eg, timeIntervalSinceReferenceDate). This way it doesn't have to be retained and disposed, etc.

get time between two times of the day

I've already tried with NSDate but with no luck.
I want the difference between for example 14:10 and 18:30.
Hours and minutes.
I Hope you can help me shouldn't be that complicated :)
There's no need to calculate this by hand, take a look at NSCalendar. If you want to get the hours and minutes between two dates, use something like this:
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:firstDate
toDate:otherDate
options:0];
[gregorianCalendar release];
You now have the hours and minutes as NSDateComponents and can access them as NSIntegers like [components hour] and [components minute]. This will also work for hours between days, leap years and other fun stuff.
Here's my quick solution:
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
[df setDateFormat:#"HH:mm"];
NSDate *date1 = [df dateFromString:#"14:10"];
NSDate *date2 = [df dateFromString:#"18:09"];
NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];
int hours = (int)interval / 3600; // integer division to get the hours part
int minutes = (interval - (hours*3600)) / 60; // interval minus hours part (in seconds) divided by 60 yields minutes
NSString *timeDiff = [NSString stringWithFormat:#"%d:%02d", hours, minutes];
The NSDate class has a method timeIntervalSinceDate that does the trick.
NSTimeInterval secondsBetween = [firstDate timeIntervalSinceDate:secondDate];
NSTimeInterval is a double that represents the seconds between the two times.
NSString *duration = [self calculateDuration:oldTime secondDate:currentTime];
- (NSString *)calculateDuration:(NSDate *)oldTime secondDate:(NSDate *)currentTime
{
NSDate *date1 = oldTime;
NSDate *date2 = currentTime;
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int hh = secondsBetween / (60*60);
double rem = fmod(secondsBetween, (60*60));
int mm = rem / 60;
rem = fmod(rem, 60);
int ss = rem;
NSString *str = [NSString stringWithFormat:#"%02d:%02d:%02d",hh,mm,ss];
return str;
}

How do I break down an NSTimeInterval into year, months, days, hours, minutes and seconds on iPhone?

I have a time interval that spans years and I want all the time components from year down to seconds.
My first thought is to integer divide the time interval by seconds in a year, subtract that from a running total of seconds, divide that by seconds in a month, subtract that from the running total and so on.
That just seems convoluted and I've read that whenever you are doing something that looks convoluted, there is probably a built-in method.
Is there?
I integrated Alex's 2nd method into my code.
It's in a method called by a UIDatePicker in my interface.
NSDate *now = [NSDate date];
NSDate *then = self.datePicker.date;
NSTimeInterval howLong = [now timeIntervalSinceDate:then];
NSDate *date = [NSDate dateWithTimeIntervalSince1970:howLong];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];
int year, month, day, hour, minute, sec;
sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minute, &sec);
year -= 1970;
NSLog(#"%d years\n%d months\n%d days\n%d hours\n%d minutes\n%d seconds", year, month, day, hour, minute, sec);
When I set the date picker to a date 1 year and 1 day in the past, I get:
1 years 1 months 1 days 16 hours 0
minutes 20 seconds
which is 1 month and 16 hours off. If I set the date picker to 1 day in the past, I am off by the same amount.
Update: I have an app that calculates your age in years, given your birthday (set from a UIDatePicker), yet it was often off. This proves there was an inaccuracy, but I can't figure out where it comes from, can you?
Brief Description
Just another approach to complete the answer of JBRWilkinson but adding some code. It can also offers a solution to Alex Reynolds's comment.
Use NSCalendar method:
(NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts
"Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". (From the API documentation).
Create 2 NSDate whose difference is the NSTimeInterval you want to break down. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval, just apply the dates to the NSCalendar method).
Get your quotes from NSDateComponents
Sample Code
// The time interval
NSTimeInterval theTimeInterval = ...;
// Get the system calendar
NSCalendar *sysCalendar = [NSCalendar currentCalendar];
// Create the NSDates
NSDate *date1 = [[NSDate alloc] init];
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
// Get conversion to months, days, hours, minutes
NSCalendarUnit unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
NSDateComponents *breakdownInfo = [sysCalendar components:unitFlags fromDate:date1 toDate:date2 options:0];
NSLog(#"Break down: %i min : %i hours : %i days : %i months", [breakdownInfo minute], [breakdownInfo hour], [breakdownInfo day], [breakdownInfo month]);
This code is aware of day light saving times and other possible nasty things.
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components: (NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit )
fromDate:startDate
toDate:[NSDate date]
options:0];
NSLog(#"%ld", [components year]);
NSLog(#"%ld", [components month]);
NSLog(#"%ld", [components day]);
NSLog(#"%ld", [components hour]);
NSLog(#"%ld", [components minute]);
NSLog(#"%ld", [components second]);
From iOS8 and above you can use NSDateComponentsFormatter
It has methods to convert time difference in user friendly formatted string.
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
NSLog(#"%#", [formatter stringFromTimeInterval:1623452]);
This gives the output - 2 weeks, 4 days, 18 hours, 57 minutes, 32 seconds
Convert your interval into an NSDate using +dateWithIntervalSince1970, get the date components out of that using NSCalendar's -componentsFromDate method.
SDK Reference
This works for me:
float *lenghInSeconds = 2345.234513;
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:lenghInSeconds];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
[formatter setDateFormat:#"HH:mm:ss"];
NSLog(#"%#", [formatter stringFromDate:date]);
[formatter release];
The main difference here is that you need to adjust for the timezone.
Or there is my class method. It doesn't handle years, but that could easily be addedn though it's better for small timelaps like days, hours and minutes. It take plurals into account and only shows what's needed:
+(NSString *)TimeRemainingUntilDate:(NSDate *)date {
NSTimeInterval interval = [date timeIntervalSinceNow];
NSString * timeRemaining = nil;
if (interval > 0) {
div_t d = div(interval, 86400);
int day = d.quot;
div_t h = div(d.rem, 3600);
int hour = h.quot;
div_t m = div(h.rem, 60);
int min = m.quot;
NSString * nbday = nil;
if(day > 1)
nbday = #"days";
else if(day == 1)
nbday = #"day";
else
nbday = #"";
NSString * nbhour = nil;
if(hour > 1)
nbhour = #"hours";
else if (hour == 1)
nbhour = #"hour";
else
nbhour = #"";
NSString * nbmin = nil;
if(min > 1)
nbmin = #"mins";
else
nbmin = #"min";
timeRemaining = [NSString stringWithFormat:#"%#%# %#%# %#%#",day ? [NSNumber numberWithInt:day] : #"",nbday,hour ? [NSNumber numberWithInt:hour] : #"",nbhour,min ? [NSNumber numberWithInt:min] : #"00",nbmin];
}
else
timeRemaining = #"Over";
return timeRemaining;
}
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// format: YYYY-MM-DD HH:MM:SS ±HHMM
NSString *dateStr = [date description];
NSRange range;
// year
range.location = 0;
range.length = 4;
NSString *yearStr = [dateStr substringWithRange:range];
int year = [yearStr intValue] - 1970;
// month
range.location = 5;
range.length = 2;
NSString *monthStr = [dateStr substringWithRange:range];
int month = [monthStr intValue];
// day, etc.
...
- (NSString *)convertTimeFromSeconds:(NSString *)seconds {
// Return variable.
NSString *result = #"";
// Int variables for calculation.
int secs = [seconds intValue];
int tempHour = 0;
int tempMinute = 0;
int tempSecond = 0;
NSString *hour = #"";
NSString *minute = #"";
NSString *second = #"";
// Convert the seconds to hours, minutes and seconds.
tempHour = secs / 3600;
tempMinute = secs / 60 - tempHour * 60;
tempSecond = secs - (tempHour * 3600 + tempMinute * 60);
hour = [[NSNumber numberWithInt:tempHour] stringValue];
minute = [[NSNumber numberWithInt:tempMinute] stringValue];
second = [[NSNumber numberWithInt:tempSecond] stringValue];
// Make time look like 00:00:00 and not 0:0:0
if (tempHour < 10) {
hour = [#"0" stringByAppendingString:hour];
}
if (tempMinute < 10) {
minute = [#"0" stringByAppendingString:minute];
}
if (tempSecond < 10) {
second = [#"0" stringByAppendingString:second];
}
if (tempHour == 0) {
NSLog(#"Result of Time Conversion: %#:%#", minute, second);
result = [NSString stringWithFormat:#"%#:%#", minute, second];
} else {
NSLog(#"Result of Time Conversion: %#:%#:%#", hour, minute, second);
result = [NSString stringWithFormat:#"%#:%#:%#",hour, minute, second];
}
return result;
}
Here's another possibility, somewhat cleaner:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:timeInterval];
NSString *dateStr = [date description];
const char *dateStrPtr = [dateStr UTF8String];
// format: YYYY-MM-DD HH:MM:SS ±HHMM
int year, month, day, hour, minutes, seconds;
sscanf(dateStrPtr, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &minutes, &seconds);
year -= 1970;