How to change year in date to current year? - iphone

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.

Related

how to compare two NSString which have date

I have two NSString which have date i want that if they both have same data then if should work otherwise else should work
here is my code
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate* date = [NSDate date];
NSString* str = [formatter stringFromDate:date];
NSString*addedDateTime=str;
if ([test isEqualToString:str]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
my code always runs else when there is same value in both i have checked using NSLog
Don't compare two NSStrings, which represent the dates, but compare two NSDates instead
First you convert string to date and use this [date1 isEqualToDate:date2].This is a compair a two date.
use this code I hope this code useful for you.
NSString*test=data.addedDateTime;
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy_MM_dd"];
NSDate* d = [df dateFromString:test];
[df release];
NSDate* date = [NSDate date];
if ([d isEqualToDate:date) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else {
[yesterdayArray addObject:theObject];
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSDate *date1 = [dateFormatter dateFromString:TodatDate];
NSDateFormatter *dateFormatte = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatte setDateFormat:#"yyyy-MM-dd"];
NSDate *date2 = [dateFormatte dateFromString:ServerDate];
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date1 toDate:date2 options:0];
int days = [comps day];
NSLog(#"%d",days);
Condition [test isEqualToString:str] always gives NO if date is either not equal or in not same formate. So dont use this.
Use NSDateComponent to compare two dates or Compare as #Andrey Gordeev
Says .
Try this code for any comparison between dates... You should not compare date in the form of string. Compare the dates before conversion to string. Convert the string "test" into date format using dateFromString function of the formatter by specifying the exact date format as that of the test. Then compare the dates using following function.
NSString*test=data.addedDateTime;
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy_MM_dd"];
NSDate *newDate = [formatter dateFromString:data.addedDateTime]; // other date
NSDate *today = [NSDate date]; // current date
NSComparisonResult result;
result = [today compare:newDate]; // comparing two dates
if(result == NSOrderedSame)
{
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}
else
{
[yesterdayArray addObject:theObject];
}
Instead of comparing String compare Date. Like this,
NSDate *myDate1 =data.addedDateTime;
NSDate* mydate2 = [NSDate date];
if ([myDate1 compare:mydate2] == NSOrderedDescending) {
NSLog(#"Dilip myDate1 is later than myDate2");
} else if ([myDate1 compare:mydate2] == NSOrderedAscending) {
NSLog(#"Dilip myDate1 is earlier than myDate2");
} else {
NSLog(#"Dilip dates are the same");
}
first u should convert date to nsstring..
then u set perfect date formate in both string..
like
NSDate *today1 = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MM-yyyy"];
NSString *dateString11 = [dateFormat stringFromDate:today1];
[dateString11 retain];
ur first string is like dateString11
and other date string is like str2=#"03-10-2010";
then u compare two string
if ([dateString11 isEqualToString:str2]) {
[todayArray addObject:theObject];
int count=[todayArray count];
NSLog(#"Today array working %d",count);
}

How can I extract the hours, min, sec from the below mentioned format

I am making an iphone application in which I want to implement the alarm concept. I am using time picker for time but I am getting the time 2011-08-17 17:00:45 +0530 in this format. Now I want to get the hours, min and seconds different by using range concept or any other concept. How can I do it. Please help me.
Thanks in advance.
Try this
NSDateFormatter *format = [[[NSDateFormatter alloc]init] autorelease];
[format setDateFormat:#"HH:mm:ss"];
NSString strTime = [NSString stringWithFormat:#"%#",[format stringFromDate:yourDate]];
And then separate the string into components :
NSArray *arr = [str componentSeparatedBy:#" "];
NSString *strHours = [arr objectAtIndex:0];
NSString *strMinutes = [arr objectAtIndex:1];
NSString *strSeconds = [arr objectAtIndex:2];
Now convert hours and minutes into seconds :
int iHours = [strHours intValue];
if(iHours>12) //Check for hour more than 12:00 eg 17:00
{
iHours = iHours - 12;
}
int iMinutes = [strMinutes intValue];
int iSeconds = [strSeconds intValue];
intTotalSeconds = (60*60*iHours) + (60*iMinutes) + iSeconds;
iTotalSeconds are the total seconds you require.
If you want to convert the String to NSDate use:
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc]init]
[format setDateFormat:#"yyyy-MM-dd HH:mm:ss ZZZZ"];
NSDate* foo = [dateFormatter dateFromString:yourDateString];
After that you can convert the NSDate to NSDateComponents and get the seconds, minutes etc. from them.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:
(NSMinuteCalendarUnit|NSSecondCalendarUnit) fromDate:foo];
NSInteger second = [component second];
NSInteger minute = [component minute];
Either do a mashup of #Nitish and #cortez's answers (use one DateFormatter to parse the date string, and another to output it in your preferred format), or:
Download and include RegexKitLite in your project.
Then go:
#import "RegexKitLite.h"
NSString *timeString = #"2011-08-17 17:00:45 +0530";
NSString *regex = #"\d{2}:\d{2}:\d{2}";
NSString *timeComponent = [timeString stringByMatching:regex capture:1];

How to use NSDate formatter with an array of dates?

I'm trying to generate an array of 30 days from the current date and put them into an array formatted correctly. I currently have a working generater to get 30 days from the current date and put it into an array but I don't know how to use NSDate formatter for an array. I know how to use the formatter for a single item but how can I format all the dates in my array? The format that I would like is (Month Day). Here's my code:
NSMutableArray* dates = [[NSMutableArray alloc] init];
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSDate *tempDate=[startDate copy];
for (int i=0;i<numberOfDays;i++) {
NSLog(#"%#",tempDate.description);
tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
[dates addObject:tempDate.description];
}
NSLog(#"%#",dates);
Any help would be appreciated, Thanks.
i suggest you to give the NSDate formatter to your date first and then give those objects to the NSMutableArray and whenever you fetch the object from an array you get the required format.
Hope you get my point...Good Luck!
use like this,
NSMutableArray* dates = [[NSMutableArray alloc] init];
int numberOfDays=30;
NSDate *startDate=[NSDate date];
NSDate *tempDate=[startDate copy];
for (int i=0;i<numberOfDays;i++) {
NSLog(#"%#",tempDate.description);
tempDate=[tempDate dateByAddingTimeInterval:(60*60*24)];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd"];
NSString *dateString = [dateFormat stringFromDate:tempDate];
tempDate=[dateFormat dateFromString:dateString];
[dateFormat release];
[dates addObject:tempDate.description];
}
NSLog(#"%#",dates);

how to add the time in iphone?

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

How can I convert a NSString representation of a time value into two NSInteger's containing the hour and minute?

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