I have three string
str1 = #"00:14";
str2 = #"00:55";
str3 = #"00:10";
i need to add the three string as a integer and display in the same time format
how can i do please help me
Thanks in Advance
Working with dates in Cocoa is fun! You could create a method like this:
- (NSDate *)dateByAddingDates:(NSArray *)dates {
NSCalendar *calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [dates objectAtIndex:0];
for (int i = 1; i < [dates count]; i++) {
NSDate *newDate = [dates objectAtIndex:i];
NSDateComponents *comps = [calendar components:unitFlags fromDate:newDate];
date = [calendar dateByAddingComponents:comps toDate:date options:0];
}
return date;
}
And use it like this:
NSString *str1 = #"00:14";
NSString *str2 = #"00:55";
NSString *str3 = #"00:10";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"mm:ss"];
NSArray *dates = [NSArray arrayWithObjects:[dateFormatter dateFromString:str1],
[dateFormatter dateFromString:str2],
[dateFormatter dateFromString:str3], nil];
NSDate *date = [self dateByAddingDates:dates];
NSLog(#"%#", [dateFormatter stringFromDate:date]);
To do things properly, it would be this:
Use an NSDateFormatter to convert the strings into NSDate objects.
Use [NSCalendar currentCalendar] to extract the NSDateComponents for each date, particularly the NSMinuteCalendarUnit.
Add up all the minutes of the date components, and set that into an NSDateComponent object
(optional) Use your calendar to convert the NSDateComponent back into an NSDate.
To do things stupidly, you'd get a substring of characters after :, invoke intValue on it to turn the string into an int, then add it all up. I don't recommend doing this, because it could lead to subtle and devious errors. Plus, there's already code in place to do it for you. :)
check out this related thread: Comparing dates
in summary, first parse the strings as NSDates using the initWithString: method call. Thereafter you can add and manipulate the dates any way you wish, and finally just format it for the right output.
Hope this hopes clarify your query.
Btw the Mac Developer SDK Reference can found here for your information:-
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDate
Related
i have one array something like below
Birthdates(
"03/12/2013",
"03/12/2013",
"08/13/1990",
"12/09/1989",
"02/06",
"09/08",
"03/02/1990",
"08/22/1989",
"03/02",
"05/13",
"10/16",
"07/08",
"08/31/1990",
"04/14/1992",
"12/15/1905",
"08/14/1989",
"10/07/1987",
"07/25",
"07/17/1989",
"03/24/1987",
"07/28/1988",
"01/21/1990",
"10/13"
)
all are NSString
now i want to make another array from this in which all years should be 2013 if that date is coming in current year and if date is already passed then change year to 2014?
in above sentence we are not considering year we consider only day and month and then see in current year is it already passed or not?
example if date is "12/15/1905" then convert it in another array like "12/15/2013"
but if date is like "01/01/1990" then convert it in another array like "01/01/2014"
bcoz it has already passed current date
plz help thank you in advance :)
i will prefer to do something in which code apply for not only 2013 and 2014 it should apply for coming future too.
This code will do for you :
NSArray *Birthdates=#[
#"03/12/2013",
#"03/12/2013",
#"08/13/1990",
#"12/09/1989",
#"02/02",
#"09/08",
#"03/02/1990",
#"08/22/1989",
#"03/02"];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger currentYear = [components year];
NSMutableArray *newBirthDates=[NSMutableArray new];
for(NSString *str in Birthdates){
NSArray *array=[str componentsSeparatedByString:#"/"];
if(array.count==2){
NSString *tempString=[NSString stringWithFormat:#"%#/%d",str,currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:tempString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
NSLog(#"passed->%# *** %#",date, str);
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%d",str,currentYear+1]];
}
[newBirthDates addObject:tempString];
}
else{
NSString *dateString=[NSString stringWithFormat:#"%#/%#/%d",array[0],array[1],currentYear];
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSDate *date=[dateFormatter dateFromString:dateString];
if ([[NSDate date] isGreaterThanOrEqualTo:date]) {
dateString=[NSString stringWithFormat:#"%#/%#/%d",array[0],array[1],currentYear+1];
}
[newBirthDates addObject:dateString];
}
}
NSLog(#"%#",newBirthDates);
Here is the Output:
DocumentBased[6632:303] (
"03/12/2014",
"03/12/2014",
"08/13/2013",
"12/09/2013",
"02/02/2014",
"09/08/2013",
"03/02/2014",
"08/22/2013",
"03/02/2014"
)
This code is same as Anoop Vaidya code upto fetching all the dateStrings into one format. but the date comparision logic which fails in Anoop code is over comed here i.e., when count == 2..
Here is my edited code respect to Anoop
NSArray *Birthdates=#[
#"03/12/2013",
#"03/12/2013",
#"08/13/1990",
#"12/09/1989",
#"02/06",
#"09/08",
#"03/02/1990",
#"08/22/1989",
#"03/02"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy"];
NSString *curYear = [dateFormatter stringFromDate:[NSDate date]];
NSString *nextYear = [NSString stringWithFormat: #"%d", ([curYear intValue] + 1)];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSMutableArray *newBirthDates=[NSMutableArray new];
for(NSString *str in Birthdates){
NSArray *array=[str componentsSeparatedByString:#"/"];
if(array.count==2){
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%#",str,curYear]];
}
else{
[newBirthDates addObject:[NSString stringWithFormat:#"%#/%#/%#",array[0],array[1],curYear]];
}
}
for(int i = 0; i < [newBirthDates count]; i++)
{
NSString *dateStr = [newBirthDates objectAtIndex:i];
NSComparisonResult comResult = [[dateFormatter dateFromString:dateStr] compare:[NSDate date]];
if(comResult == NSOrderedAscending)
{
[dateStr stringByReplacingOccurrencesOfString:curYear withString:nextYear];
[newBirthDates replaceObjectAtIndex:i withObject:dateStr];
}
}
NSLog(#"%#",newBirthDates);
This will work in all the scenarios...
I take it you know how to use the NSDateFormatter to format dates, to change the year alone, just check this link NSDateComponents. Please have a look at this StackOverflow question on how to split the date into NSDateComponents.
I think You can check it directly without using dateFormatter.
Steps to do:
First find the current date with NSDate.Convert it into string and make the format as same the array you have, by using NSDateFormatter.
Next compare one by one by making condition .
Separate the string by "/" .
if([myArray objectAtIndex:i]string separate by#"/" objectAtIndex:0 )
and the check the next one ...
Make the condition as you want
I hope if you do like this with less lines of code you can achieve what you want.
Here I'm trying to calculate the hours between two dates. When i run the application, it crashes. Could you please tell me the mistake in this code?
NSString *lastViewedString = #"2012-04-25 06:13:21 +0000";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat: #"yyyy-MM-dd HH:mm:ss zzz"];
NSDate *lastViewed = [[dateFormatter dateFromString:lastViewedString] retain];
NSDate *now = [NSDate date];
NSLog(#"lastViewed: %#", lastViewed); //2012-04-25 06:13:21 +0000
NSLog(#"now: %#", now); //2012-04-25 07:00:30 +0000
NSTimeInterval distanceBetweenDates = [now timeIntervalSinceDate:lastViewed];
double secondsInAnHour = 3600;
NSInteger hoursBetweenDates = distanceBetweenDates / secondsInAnHour;
NSLog(#"hoursBetweenDates: %#", hoursBetweenDates);
Referring to this answer of a mostly similar question a better and Apple approved way would be using the NSCalendar methods like this:
- (NSInteger)hoursBetween:(NSDate *)firstDate and:(NSDate *)secondDate {
NSUInteger unitFlags = NSCalendarUnitHour;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:unitFlags fromDate:firstDate toDate:secondDate options:0];
return [components hour]+1;
}
If you target iOS 8 or later use NSCalendarIdentifierGregorian instead of the deprecated NSGregorianCalendar.
I think difference should be in int value...
NSLog(#"hoursBetweenDates: %d", hoursBetweenDates);
Hope, this will help you..
NSInteger can't be shown by using
NSLog(#"%#", hoursBetweenDates);
instead use:
NSLog(#"%d", hoursBetweenDates);
If unsure what to use look in the Apple Developer Docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265
I want to find a date by providing a weekday. For instance, I want to find the date of last Sunday and this Sunday. How to do it in iOS?
In OSX, NSDate provides a method of dateWithNaturalLanguageString, but iOS does not provide a similar method. Please help me.
Thanks.
you can calculate using NSDateComponents..
This is Sample. It helps you.
NSDate *date = [NSDate date];
NSString *dateString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterLongStyle
timeStyle:NSDateFormatterNoStyle];
NSString *timeString = [NSDateFormatter localizedStringFromDate:date
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterShortStyle];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
int weekday = [[currentCalendar components:NSWeekdayCalendarUnit fromDate:date] weekday];
NSString *weekdayString = [[[NSDateFormatter alloc] shortWeekdaySymbols] objectAtIndex:weekday-1];
Im using an NSCalendar to display the week day, I have no problem displaying the weekday in an integer, but i am confused as to how i might get it to tell me the weekday, i.e. "Thursday." I read that %A, and %a might do the trick but I do not know how to implement them. My code is below.
NSDate* now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:now];
NSInteger weekday = [weekdayComponents weekday];
myLabel.text = [NSString stringWithFormat:#"%02d", weekday];
I use myLabel to display the string on the Iphone, but if there is a better way please let me know.
Thanks for the help.
James
To display day of week you actually need to use NSDateFormatter class, set 'EEEE' format to get full day name (like Thursday) or 'EEE' - for shortened (like Thu). Very sample code:
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"EEEE"];
NSLog([f stringFromDate:[NSDate date]]);
I'm diving into iOS development and the Objective C language and am building an alarm clock app to become familiar with the SDK and language. I have an NSString object that represents a time, with the range "1:00 am" to "12:59 am". I need to convert this NSString into two NSInteger's that contain the hour value and minute value. As I'm doing this, I'm finding the NSString manipulation that I'm doing to be extremely laborious and it just feels like sloppy code.
Is there a simple way to extract the hour and minute characters from a NSString representation of a time value and store their numerical values in two NSInteger's?
Thanks in advance for all your help! I'm gonna get back to it...
NSScanner* timeScanner=[NSScanner scannerWithString:...the time string...];
int hours,minutes;
[timeScanner scanInt:&hours];
[timeScanner scanString:#":" intoString:nil]; //jump over :
[timeScanner scanInt:&minutes];
NSLog(#"hours:%d minutes:%d",hours,minutes);
Use an NSDateFormatter to convert your string into an NSDate.
Use the [NSCalendar currentCalendar] to extract various date components (like the hour, minute, etc).
In other words:
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"h:m a"];
NSDate *date = [formatter dateFromString:#"12:59 pm"];
[formatter release];
NSDateComponents * components = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:date];
NSLog(#"hour: %d", [components hour]);
NSLog(#"minute: %d", [components minute]);
This is the official way, as I know it. It's not pretty:
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc]init] autorelease];
[dateFormatter setDateFormat:#"h:m a"];
NSDate *date = [dateFormatter dateFromString:#"12:34 am"];
[dateFormatter setDateFormat:#"h"];
NSString *hours = [dateFormatter stringFromDate:date];
[dateFormatter setDateFormat:#"m"];
NSString *minutes = [dateFormatter stringFromDate:date];
BUT the string fiddling way of doing it (look for :, look for space, ...), may give you more headaches on the long term.
NSString *time = #"1:00 am";
NSString *removeam = [time stringByReplacingOccurencesOfString:#" am" withString:#""];
SString *removepm = [removeam stringByReplacingOccurencesOfString:#" pm" withString:#""];
NSArray *timeArray = [removepm componentsSeparatedByString:#":"];
NSInteger *hour = [[timeArray objectAtIndex:0] intValue];
NSInteger *mins = [[timeArray objectAtIndex:1] intValue];
If you're building an alarm clock app, you probably will want to look into the NSDate and NSDateFormatter classes, instead of trying to pull all those strings apart into integer types. Also, your time range is a bit weird (maybe a typo?) - don't you want all 24 hours to be available?
get the time interval and write it as
duration.text = [NSString stringWithFormat:#"%d:%02d", (int)audioPlayer.duration / 60, (int)audioPlayer.duration % 60, nil];