hours minutes seconds to seconds ios - iphone

I want to convert time hours minutes seconds to seconds in ios.
Is there any in built method for this?
How can I do this?
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsDiff = [gregorianCalendar components:NSHourCalendarUnit fromDate:[NSDate date]];

Following code for the insert date as a string and then return numbers of second.
- (NSNumber *)dateToSecondConvert:(NSString *)string {
NSArray *components = [string componentsSeparatedByString:#":"];
NSInteger hours = [[components objectAtIndex:0] integerValue];
NSInteger minutes = [[components objectAtIndex:1] integerValue];
NSInteger seconds = [[components objectAtIndex:2] integerValue];
return [NSNumber numberWithInteger:(hours * 60 * 60) + (minutes * 60) + seconds];
}
May this help to lot.

Maybe I misunderstand the question but this will give you current time in seconds from 1970
[[NSDate date] timeIntervalSince1970]

Plenty of examples, but this what you can do:
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *comp = [calendar components:NSHourCalendarUnit fromDate:now];
//[comp hour]
//[comp minute]
//[comp second]

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

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

Count Down Timer in iPhone

I have two time.. one fetched directly as string(#"21:00") and other is the current time. I want to display a count down timer showing how much time left from now to reach 21:00.
For eg: the label i use should display "You have 3hrs and 30 minutes left.." if the current time is 17:30.
thanks..
OK have completely revised my answer, and have created a complete solution to the problem, with fully tested sample code available on github.
Enjoy :)
Something like this should do it. This will give you the remaining time in seconds. Then you just need to to standard timer stuff as indicated in other answers.
//assumption: targetTime is after now
NSString *targetTime = #"21:00";
//split our time into components
NSArray *timeSplit = [targetTime componentsSeparatedByString:#":"];
NSUInteger hours = [[timeSplit objectAtIndex:0] intValue];
NSUInteger minutes = [[timeSplit objectAtIndex:1] intValue];
NSDate *now = [NSDate date];
//split now into year month day components
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [currentCalendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:now];
//set our time components from above
[dateComponents setHour:hours];
[dateComponents setMinute:minutes];
NSDate *targetDate = [currentCalendar dateFromComponents:dateComponents];
//ensure target is after now
if ([targetDate timeIntervalSinceDate:now] < 0)
{
NSDateComponents *day = [[NSDateComponents alloc] init];
[day setDay:1];
targetDate = [currentCalendar dateByAddingComponents:day toDate:targetDate options:0];
}
NSTimeInterval timeRemaining = [targetDate timeIntervalSinceDate:now];
You create a NSTimer that fires every second:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(tickClock) userInfo:nil repeats:YES];
When it fires, you enter a method:
- (void)tickClock;
in there, you compare the date you have against the current date [NSData currentDate];
Like
NSTimeInterval distanceBetweenDates = [currentDate timeIntervalSinceDate:yourDate];
where distanceBetweenDates is specified in seconds.
To create a date from your string create a NSDate accordingly
NSInteger year = 2011;
NSInteger month = 8;
NSInteger day = 26;
NSInteger hour = 21;
NSInteger minute = 0;
NSInteger second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:year];
[components setMonth:month];
[components setDay:day];
[components setHour:hour];
[components setMinute:minute];
[components setSecond:second];
NSDate *date = [calendar dateFromComponents:components];
[components release];

Find exact difference between two dates

I want some changes in the date comparison.
In my application I am comparing two dates and getting difference as number of Days, but if there is only one day difference the system shows me 0 as a difference of days.
NSDateFormatter *date_formater=[[NSDateFormatter alloc]init];
[date_formater setDateFormat:#"MMM dd,YYYY"];
NSString *now=[NSString stringWithFormat:#"%#",[date_formater stringFromDate:[NSDate date]]];
LblTodayDate.text = [NSString stringWithFormat:#"%#",[NSString stringWithFormat:#"%#",now]];
NSDate *dateofevent = [[NSUserDefaults standardUserDefaults] valueForKey:#"CeremonyDate_"];
NSDate *endDate =dateofevent;
NSDate *startDate = [NSDate date];
gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
unsigned int unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int days = [components day];
I found some solutions that If we make the time as 00:00:00 for comparison then it will show me proper answer, I am right or wrong I don't know.
i think this is not correct make the time 00:00:00.
may be you get difference is less than 24 hour thats why it rounded off and you 0 day.
Alexander solution is right so use that solution like -
this works fine for me also.
NSDate *endDate=[dateFormat dateFromString:now];
NSTimeInterval interval = [CeremonyDate timeIntervalSinceDate:endDate];
int diff=interval/86400;//for converting seconds into days.
same problem of rounding a figure you get here but you can sort out that in an understable way.
I usually find out difference in seconds and calculate ceil(diffInSeconds / 86400).
Try this code for get two date and time different.
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease]];
[dateFormatter setDateFormat:#"mm:ss"];
NSDate* firstDate = [dateFormatter dateFromString:#"04:45"];
NSDate* secondDate = [dateFormatter dateFromString:#"05:00"];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"%f",timeDifference);
i hope this code usefull for you.
Here a prefect solution to find difference between two dates
- (NSString *)calculateDuration:(NSDate *)oldTime secondDate:(NSDate *)currentTime
{
NSString *timeSincePost;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:oldTime toDate:currentTime options:0];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger second = [dateComponents second];
if (year) {
timeSincePost = [NSString stringWithFormat:#"%ld%#", (long)year,[[kAppDelegate languageBundle] localizedStringForKey:#"y" value:#"" table:nil]];
}
else if (month) {
timeSincePost = [NSString stringWithFormat:#"%ld%#", (long)month,[[kAppDelegate languageBundle] localizedStringForKey:#"M" value:#"" table:nil]];
}
if(day) {
timeSincePost = [NSString stringWithFormat:#"%ld%#", (long)day,[[kAppDelegate languageBundle] localizedStringForKey:#"d" value:#"" table:nil]];
}
else if(hour) {
timeSincePost = [NSString stringWithFormat: #"%ld%#", (long)hour,[[kAppDelegate languageBundle] localizedStringForKey:#"H" value:#"" table:nil]];
}
else if(minute) {
timeSincePost = [NSString stringWithFormat: #"%ld%#", (long)minute,[[kAppDelegate languageBundle] localizedStringForKey:#"m" value:#"" table:nil]];
}
else if(second)
timeSincePost = [NSString stringWithFormat: #"%ld%#", (long)second,[[kAppDelegate languageBundle] localizedStringForKey:#"s" value:#"" table:nil]];
return timeSincePost;
}
and call above function with two parameter as NSDate
NSString *duration = [self calculateDuration:postDate secondDate:[NSDate date]];
lblPostTime.text = duration;
note:: postDate is FirstDate & second date is current date..

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