Convert NSString to a Time, and then calculate "Time Until" - iphone

I have been on SO for awhile now trying to get this problem solved but have not had any luck.
In a nutshell I want to take a string like this: "2011-11-21 11:20:00" and calculate the "Time Until".
In a format like "1 day 36 mins" which would be a string I could display in a label.
I cant wrap my head around this. Anyone have some sample code from doing this before? Any help would be greatly appreciated.

#Maudicus is on the right track but has some flaws in his answer.
The date format you'd need to use is #"yyyy-MM-dd HH:mm:ss"
Once you have the date, you should use -[NSCalendar components:fromDate:toDate:options:] to figure out the differences between one date and another. For example:
NSDate *date = ...; // the date converted using the date formatter
NSDate *target = [NSDate date]; // now
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger components = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *difference = [calendar components:components fromDate:date toDate:target options:0];
NSLog(#"difference: %d days, %d hours, %d minutes, %d seconds", [difference days], [difference hours], [difference minutes], [difference seconds]);

This code should help you out.
NSDate * date;
//Assume dateString is populated and of format NSString * dateString =#"2011-11-21 11:20:00";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
//EDITED date formatter to correct behavior
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
if (dateString != nil) {
date = [dateFormatter dateFromString:dateString];
}
[dateFormatter release];
NSTimeInterval difference = [date timeIntervalSinceDate:[NSDate date]];
int days = difference/(3600*24);
difference -= (float) (days*3600*24);
int hours = difference/(3600);
difference -= (float) (hours*3600);
int minutes = difference/(60);
NSString * timeRemaining = [NSString stringWithFormat:#"%dd %dh %dm", days, hours, minutes];

duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 3600, (int)audioPlayer.duration % 60, nil];

Related

Check whether a specified date is today, yesterday, or a future date

I have one query regarding NSDate. I have a date i.e. "2011-10-04 07:36:38 +0000", and I want to check if this date is yesterday, or today or a future date.
How would I go about this?
Try this:
Note: Change the date format as per your need.
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSDate* enteredDate = [df dateFromString:#"10/04/2011"];
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:enteredDate];
switch (result)
{
case NSOrderedAscending:
NSLog(#"Future Date");
break;
case NSOrderedDescending:
NSLog(#"Earlier Date");
break;
case NSOrderedSame:
NSLog(#"Today/Null Date Passed"); //Not sure why This is case when null/wrong date is passed
break;
}
See Apple's documentation on date calculations:
NSDate *startDate = ...;
NSDate *endDate = ...;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
NSInteger months = [components month];
NSInteger days = [components day];
If days is between +1 and -1 then your date is a candidate for being "today". Obviously you'll need to think about how you handle hours. Presumably the easiest thing would be to set all dates to be 00:00.00 hours on the day in question (truncate the date using an approach like this), and then use those values for the calculation. That way you'd get 0 for today, -1 for yesterday, +1 for tomorrow, and any other value would likewise tell you how far things were in the future or the past.
Use any of the folowing according to ur need,
– earlierDate:
– laterDate:
– compare:
Refer this http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
-(NSString*)timeAgoFor:(NSString*)tipping_date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:tipping_date];
NSString *key = #"";
NSTimeInterval ti = [date timeIntervalSinceDate:[NSDate date]];
key = (ti > 0) ? #"Left" : #"Ago";
ti = ABS(ti);
NSDate * today = [NSDate date];
NSComparisonResult result = [today compare:date];
if (result == NSOrderedSame) {
return[NSString stringWithFormat:#"Today"];
}
else if (ti < 86400 * 2) {
return[NSString stringWithFormat:#"1 Day %#",key];
}else if (ti < 86400 * 7) {
int diff = round(ti / 60 / 60 / 24);
return[NSString stringWithFormat:#"%d Days %#", diff,key];
}else {
int diff = round(ti / (86400 * 7));
return[NSString stringWithFormat:#"%d Wks %#", diff,key];
}
}

How to take a integer day from date format?

i want a day in digits from my Current date.for an example
if entry_date = August 22, 2011
due_on = "Due on 22nd"
i know the logic of getting suffix,but how to get day value from my current date.
You can get day from current date as follows:
NSDate * mCurrentDate = [NSDate date];
NSCalendar * calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents * weekdayComponents = [calendar components:NSDayCalendarUnit fromDate: mCurrentDate];
_day = [weekdayComponents day];
This will give you the day component of your current date.
(According to your example) try this ....
NSString *entry_date = #"August 22, 2011";
NSString *digits = [entry_date stringByTrimmingCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
int intDate = [digits intValue]
NSLog(#"Attempts: %d", intDate);
Hope its helps you... :D

Convert String to Date and fetch the difference

hi i have 2 dates in string format
base_date_string = 10-12-01 12:00:00
current_date_string = 10-12-23 10:18:00
both the above values are in string
i want to get the number of days elapsed between these 2 dates
I tried to convert them to NSDate using NSDateFormatters and then getting the difference.
I realised that string does not properly converts to NSDate
when i convert to nsdate i got
base_date:::2010-12-01 06:30:00 +0000
current_date::::2010-12-23 04:48:19 +0000 (the time portion is not perfect)
Formatter class that i used is:
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
[formatter1 release];
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter2 release];
//subrtrcation of basedate from current date to get elapsed number of days
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *diff = [calendar components:(NSDayCalendarUnit)
fromDate:base_date toDate:current_date options:0];
int date_value = [diff day];
Please any help is appreciated
30 seconds in the NSDate documentation revealed:
-[NSDate timeIntervalSinceDate:]
So using the dates in your question...
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
difference = fabs(difference);
NSLog(#"there are %f seconds between %# and %#", difference, current_date, base_date);
edit
ok, so the problem is not date differencing. You're observing that the string you're inputting is 5 and 1/2 hours ahead of the date you're getting back.
Well, let's look at this. The date returned is in GMT time (as denoted by the +0000). 5 and 1/2 hours ahead of that is the timezone used in India. So. Are you in India? If you are, then this is just a matter of needing to -setTimezone: on your NSDateFormatter.
You can use this code of function to get the difference between 2 dates
-(int)howManyDaysHavePast:(NSDate*)lastDate :(NSDate*)today {
NSDate *startDate = lastDate;
NSDate *endDate = today;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags
fromDate:startDate
toDate:endDate options:0];
[gregorian release];
int days = [components day];
return days;
}
hAPPY iCODING...
Use the following code
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"yy-MM-dd HH:mm:ss"];
NSDate *base_date = [formatter1 dateFromString:#"10-12-01 12:00:00"];
NSDate *current_date = [formatter2 dateFromString:current_date_string];
[formatter1 release];
NSTimeInterval difference = [current_date timeIntervalSinceDate:base_date];
Then you will get difference in number of seconds. Then you can get in number of days as following
float days = difference/86400;
The "days" consists the number of days that the current_date is differ from the base_date.

How to find last day of week in iPhone?

In my application I'm using following codes to retrieve current date and day :-
NSDate *today1 = [NSDate date]; NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:#"dd/MM/yyyy :EEEE"]; NSString *dateString11 = [dateFormat stringFromDate:today1];
NSLog(#"date: %#", dateString11);
//[dateFormat release];
NSCalendar *gregorian11 = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];  
NSDateComponents *components1 = [gregorian11 components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:today1];
[components1 setDay:([components1 day]-([components1 weekday]-1))];
NSDate *beginningOfWeek1 = [gregorian11 dateFromComponents:components1];
NSDateFormatter *dateFormat_first = [[NSDateFormatter alloc] init];
[dateFormat_first setDateFormat:#"dd/MM/yyyy :EEEE"];
NSString *dateString_first = [dateFormat_first stringFromDate:beginningOfWeek1];
NSLog(#"First_date: %#", dateString_first);
[components1 setDay:([components1 day]-([components1 weekday]-1) + 6)]; now =[gregorian dateFromComponents:components1]; [format setDateFormat:#"dd/MM/yyyy :EEEE"]; dateString = [format stringFromDate:now]; NSLog(#" week Last_date: %#", dateString);
but using above code I only got the current day and Date and first day of week but I need to get last day of week. But it gives the wrong output. Where am I wrong in my code and what modification is needed to get last day/date of week?
When you call setDay: you are sometimes setting it to a negative day. I don't know if setDay and/or dateFromComponents: will handle that.
To create a NSDate for a date/time that is in the past (or future) you can subtract (or add) the number of seconds that you want to go back (or forward), like this:
// convert to seconds
NSTimeInterval tmpSecs = [[NSDate date] timeIntervalSinceReferenceDate];
// Shift the date/time (in seconds) to a new date X days away:
tmpSecs += daysOffset * 86400; // 86400 seconds per day
// convert back to NSDate and return the result
return [NSDate dateWithTimeIntervalSinceReferenceDate:tmpSecs];

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