how to compare two NSString which have date - iphone

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

Related

Satrt date and end date validation

I have start date and end date in string format.i want to compare end date and start date,end date should be greater than start date.How to do this.
NSLog(#"%#",date);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"dd MM yyyy"];
_start_date = [[NSDate alloc] init];
_start_date = [df dateFromString: date];
NSLog(#"date: %#", _start_date);`
Getting nil on start_date.
You need to convert both the strings to NSDate objects using NSDateFormatter.
As your date is in dd-MM-yy format, do as shown below :
NSString *dateStr1 = #"21-3-14";
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"dd-MM-yy"];
NSDate *date1 = [dateFormatter dateFromString:dateStr1];
Similarly create another date, say date2 Then you can compare these dates.
if ([date1 compare:date2] == NSOrderedDescending) {
NSLog(#"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
NSLog(#"date1 is earlier than date2");
} else {
NSLog(#"dates are the same");
}
Create an instance of NSDateFormatter.
Configure it.
Parse the strings to get NSDate objects (dateFromString:).
Compare them (compare:).

finding out days remain from array of dates [duplicate]

This question already has answers here:
How to make another array containing number of days remain
(3 answers)
Closed 9 years ago.
i have one array something like below
_combinedBirthdates(
"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"
)
this all are NSString
i am trying to make new array from this which contains days remaining something like below
(days remaining for particular birthdate)
(we will compair current date with above date array and we will find out remaining days)
_newarray(
"125",
"100",
"65",
and till end like this..
)
i am using below code for this
unsigned int unitFlags = NSDayCalendarUnit;
NSCalendar *currCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSLog(#" currCalendar%#",currCalendar);
NSMutableArray * _newarray = [[NSMutableArray alloc] init];
for (NSString * str in _combinedBirthdates){
NSDate * toDate = [dateFormatter dateFromString:str];
NSDateComponents *daysInfo = [currCalendar components:unitFlags fromDate:[NSDate date] toDate:toDate options:0];
int days = [daysInfo day];
[_newarray addObject:[NSString stringWithFormat:#"%d",days]];
}
NSLog(#" _newarray%#",_newarray);
and this is what i am getting as output when i print _newarray plz help me thank you
_newlymadeArray(
"-1",
"-1",
"-8248",
"-8495",
"-4454",
"-4454",
"-8412",
"-8604",
"-4454",
"-4454",
"-4454",
"-4454",
"-8230",
"-7638",
"-39170",
"-8612",
"-9289",
"-4454",
"-8640",
"-9486",
"-8994",
"-8452",
"-4454",
"-2072",
"-888",
"-8315"
)
Please try to use this.I think this one may help you.
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/yyyy"];
NSString *str = [tempFormatter stringFromDate:#"yourStartDate"];
NSDate *startdate = [tempFormatter dateFromString:str];
str = [tempFormatter stringFromDate:#"yourEndDate"];
NSDate *endDate = [tempFormatter dateFromString:str];
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
use below code to compare two dates pass both date in same format
NSDateFormatter *dateformat = [[NSDateFormatter alloc]init];
[dateformat setDateFormat:#"dd/MM/yyyy"];
NSString *StrDate1 = [dateformat stringFromDate:[NSDate date]];
NSString *StrDate2 = [dateformat stringFromDate:date2];
NSDate *firstDate = [dateformat dateFromString:StrDate1];
NSDate *secondDate = [dateformat dateFromString:StrDate2];
NSTimeInterval lastDiff = [firstDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = todaysDiff - lastDiff;
int day = dateDiff/(3600*24);
// days are remaining
use this in for loop you will gate remaining days

How to sort NSArray with date time values?

I have an NSArray containing date/time NSStrings in the following format:
2/2/2011 2:46:39 PM
2/4/2011 11:59:47 AM
…
where the date is represented as month/day/year.
How do I sort this NSArray making sure the newest date/times are at the top?
When you’re dealing with dates, use NSDate instead of NSString. Also, it’s important to consider the time zone — does the Web service provide dates in UTC or some other time zone?
You should first convert your array of strings into an array of dates. Otherwise, you’d be converting a string to a date whenever it is used for comparison, and there will be more comparisons than the number of strings.
For example:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
NSMutableArray *dateArray = [NSMutableArray array];
for (NSString *dateString in array) {
NSDate *date = [formatter dateFromString:dateString];
if (date) [dateArray addObject:date];
// If the date is nil, the string wasn't a valid date.
// You could add some error reporting in that case.
}
This converts array, an array of NSStrings, to dateArray, a mutable array of NSDates. The date formatter uses the system time zone. If you want to use UTC as the time zone:
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
Having done that, sorting the array is trivial:
[dateArray sortUsingSelector:#selector(compare:)];
Use method compare to compare two dates,
Sample NSDate comparision,
NSDate *dateOne = [NSDate dateWithString:#"2008-12-04 03:00:00 +0900"];
NSDate *dateTwo = [NSDate dateWithString:#"2008-12-04 04:00:00 +0900"];
switch ([dateOne compare:dateTwo]){
case NSOrderedAscending:
NSLog(#”NSOrderedAscending”);
break;
case NSOrderedSame:
NSLog(#”NSOrderedSame”);
break;
case NSOrderedDescending:
NSLog(#”NSOrderedDescending”);
break;
}
Use you own logic to sort
use this
NSMutableArray *mutArr=[yourArray mutableCopy];//convert your NSArray into mutable array
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorealese];
[df setDateFormat:#"MM/DD/YYYY hh:mm:ss a"];
NSDate *compareDate;
NSInteger index;
for(int i=0;i<[mutArray count];i++)
{
index=i;
compareDate=[df dateFromString:[mutArray objectAtIndex:i]];
NSDate *compareDateSecond;
for(int j=i+1;j<counter;j++)
{
compareDateSecond=[df dateFromString:[mutArr objectAtIndex:j]];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedAscending)
{
compareDate=compareDateSecond;
index=j;
}
}
if(i!=index)
[mutArr exchangeObjectAtIndex:i withObjectAtIndex:index];
}
}
NSLog(#"%#",mutArr);

Compare current time with fixed time 05:00:00 PM

How will I compare current time [NSDate date] with fixed time 05:00:00 PM.
That 05:00 PM is already passed or not. I just need BOOL check for this.
- (BOOL)past5pm
{
NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [gregorianCalender components:NSHourCalendarUnit fromDate:[NSDate date]];
if([components hour] >= 17) // NSDateComponents uses the 24 hours format in which 17 is 5pm
return YES;
return NO;
}
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"HH.mm"];
NSDate *currentDate = [NSDate date];
NSString *curDate = [dateFormatter stringFromDate:currentDate];
if ([curDate doubleValue] >= 17.00)
{
//set your bool
}
Try this
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:#"hh:mm:ss a"];
NSDate* date = [NSDate date];
//Get the string date
NSString* str = [dateFormatter stringFromDate:date];
NSDate *firstDate = [dateFormatter dateFromString:#"05:00:00 PM"];
NSDate *secondDate = [dateFormatter dateFromString:str];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSLog(#"Time Diff - %f",timeDifference);
You can probably use plain C style code and get the difference as an integer and then decide what you need to return from the comparison function depending on wether the difference is positive or negative. You can compare minutes this way as well. Dont forget to import time.h.
time_t now = time(NULL);
struct tm oldCTime;
localtime_r(&now, &oldCTime);
int hours = oldCTime.tm_hour;
int diff = 17-hours;
NSLog(#"Time difference is: %d.", diff);

How to find days between dates stored in 2 strings

I have two strings both are in following date format (2011-03-22).
i have to compare them and find number of days between them.
Can anyone tell me how to do this..
Please also tell me the correct method to convert them back to NSDate.
Might be a couple of errors as i just typed this, but it speaks for itself and you should get the idea.
NSString *dateStringA = #"2011-03-22";
NSString *dateStringB = #"2011-03-27";
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
df.dateFormat = #"yyyy-MM-dd";
NSDate *dateA = [df dateFromString:dateStringA];
NSDate *dateB = [df dateFromString:dateStringB];
NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSDayCalendarUnit fromDate:dateA toDate:dateB options:0];
int daysBetweenDates = comps.day; //This is your days between the 2 dates
NSDate *intervalDate = [[NSCalendar currentCalendar] dateFromComponents:comps]; //This date object represents the duration between them
 For string to date
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];
for date to string
NSString *date = [[NSDate date] description];