NSString compare is throwing exception SIGABT - iphone

I have following code, where I'm comparing two string but its throwing exception.
- (void)calendarMonthView:(TKCalendarMonthView *)monthView didSelectDate:(NSDate *)d {
NSLog(#"calendarMonthView didSelectDate %#",d);
//[self papulateTable];
//[table reloadData];
//[self performSelector:#selector(papulateTable) withObject:nil afterDelay:1.0];
NSString *tempDate = (NSString*)d;
NSString *selectedDate = #"2013-02-04 00:00:00 +0000";
if([tempDate isEqualToString:selectedDate])
{
flagtoCheckSelectedCalendarDate = 1;
}
if(flagtoCheckSelectedCalendarDate == 1)
{
[self viewDidLoad];
}
if(flagtoCheckSelectedCalendarDate == 2)
{
[self viewDidLoad];
}
//[table reloadData];
}
Could any one please suggest.Thanks.

Casting an NSDate object to NSString does not make it a string. To compare dates, you're going to have to transform the NSString into an NSDate using an NSDateFormatter. After that, you can use NSDate's instance method isEqualToDate: for your comparison.
NSString *selectedDate = #"2013-02-04 00:00:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"UTC"]];
[dateFormatter setDateFormat:#"yyyy-MM-DD hh:mm:ss ZZZZ"];
NSDate *actualDate = [dateFormatter dateFromString:selectedDate];
if ([actualDate isEqualToDate:d]) {
...
}

d is of type NSDate and not NSString, therefore -isEqualToString: results in a crash.
You shouldn't compare strings here, but the dates. Use NSDate's -compare: method and change
NSString *selectedDate = #"2013-02-04 00:00:00 +0000";
to
NSDate *selectedDate = [NSDate ...];

You are casting an NSDate object to NSString without converting it. You will have to format the NSDate as a string into your expected date format before you can compare it with your selectedDate. See this previous answer or this one for examples

You are comparing NSDate and NSString. You would need to change the NSDate to string using a date formatter first.

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

NSInvalidArgumentException, reason: 'Invalid type in JSON write (__NSDate)'

I'm getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
FIrst store your data in NSString. And then convert your string to NSDate.
You can refer SO:
Converting NSString to NSDate (and back again)
NSString to NSDate conversion problem
How to convert NSString to NSDate using NSDateFormatter?
Convert NSDate to NSString and try to encode.
- (NSString *) changeDateToDateString :(NSDate *) date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
NSLocale *locale = [NSLocale currentLocale];
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:#"hh mm" options:0 locale:locale];
[dateFormatter setDateFormat:dateFormat];
[dateFormatter setLocale:locale];
NSString *dateString = [dateFormatter stringFromDate:date];
return dateString;
}
As noted, you must first convert your NSDate to an NSString. It's not immediately clear, however, which format the date should be represented in. The answer can be found here: "JSON itself does not specify how dates should be represented, but Javascript does" -- ISO8601.
Here is an ISO8601 conversion method from a helper category for NSDate, courtesy Erica Sadun:
- (NSString *)ISO8601 {
struct tm time;
time_t interval = [self timeIntervalSince1970];
gmtime_r(&interval, &time);
char *x = calloc(1, 21);
strftime_l(x, 20, "%FT%TZ", &time, gmtlocale);
NSString *string = [NSString stringWithUTF8String:x];
free(x);
return string;
}
If you get an ISO8601 string back in a JSON payload and want to convert it to an NSDate, use this class method for NSDate:
+ (NSDate *)dateFromISO8601:(NSString *)string {
if(!string) return nil;
if (![string isKindOfClass:[NSString class]]) return nil;
struct tm time;
strptime_l([string UTF8String], "%FT%TZ", &time, gmtlocale);
return [NSDate dateWithTimeIntervalSince1970:timegm(&time)];
}
Have you tried ?
updateDate = [NSNumber numberWithFloat:[[NSDate date] timeIntervalSince1970]];
As Described Here : SDK not supporting NSDate objects
Follow these Steps :
1. Convert the Date in JSON Format :
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease];
[formatter setDateFormat:#"Z"];
NSString *updateDate = [NSString stringWithFormat:#"/Date(%.0f000%#)/", [[NSDate date] timeIntervalSince1970],[formatter stringFromDate:[NSDate date]]];
2. Embed In some array and POST the array.
The simplest way to store and retrieve a NSDate object in JSON would be to use the timeIntervalSince1970 property of NSDate.
The returned NSTimeInterval (double) is pretty standard and can easily be converted back to a NSDate object using:
NSDate dateWithTimeIntervalSince1970:<#(NSTimeInterval)#>
You must convert the date to a string before you try to encode it. There are enough examples everywhere so it should be easy to find
For our case, we are using Mantle to convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer
#property (nonatomic) NSDate *expiryDate;
where:
+ (NSValueTransformer *)expiryDateJSONTransformer {
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter dateFromString:dateString];
} reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter stringFromDate:date];
}];
}
+ (NSDateFormatter *)dateFormatter {
NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = #"yyyy-MM-dd";
return df;
}
I am doing something like this in my body params encoder
// handle dates
var _params = [String: Any]()
params.forEach { (key, value) in
if let date = value as? Date {
_params[key] = DateFormatter.iso8601Full.string(from: date)
} else {
_params[key] = value
}
}
return try? JSONSerialization.data(withJSONObject: _params)

NSDateFormatter does return what is expected

I created a method to return the NSDate from a NSString. Code is below. I send to the function "2/25/2011". The function returns "2010-12-26 08:00:00 +0000"
What did I do wrong? Also the NSString I need to release at the end. How do I do that?
thank you!
-(NSDate *) GetDatefromString:(NSString *) Str
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM-dd-YYYY"];
NSDate *dateFromString;
// = [[NSDate alloc] init]; tried taking this part out but still not working
if (Str != NULL)
{
dateFromString = [formatter dateFromString:Str];
}
else
{
dateFromString = [formatter dateFromString:#"1/1/1970"];
}
[formatter release];
return dateFromString;
// how do I release dateFromString?
/*
Printing description of dateFromString:
2010-12-26 08:00:00 +0000
Printing description of Str:
02-25-2011
*/
}
You are passing in a date using the / seperator but you specified - as a separator for your date formatter. As to your question on releasing the string, you should only release objects that you own, i.e. that you have created with new, alloc, copy, or mutableCopy. See examples below.
NSDateFormatter* formatter = [[NSDateFormatter alloc] init]; // needs releasing
[formatter setDateFormat:#"MM-dd-yyyy"];
NSString* str1 = #"06/25/2011"; // does not need releasing
NSString* str2 = [[NSString alloc] initWithString:#"06-25-2011"]; // needs releasing
NSDate* date1 = [formatter dateFromString:str1]; // does not need releasing
NSDate* date2 = [[NSDate alloc] init]; // needs releasing
date2 = [formatter dateFromString:str2];
NSLog(#"date from %# : %#", str1, date1);
NSLog(#"date from %# : %#", str2, date2);
// release the objects you own
[formatter release];
[str2 release];
[date2 release];
// prints out
date from 06/25/2011 : (null)
date from 06-25-2011 : 2011-06-25 00:00:00 -0700
you set the format to#"MM-dd-YYYY"but the string you pass in has the form #"1/1/1970". That doesn't match. see Data Formatting Guide: Date formatters.
// how do I release dateFromString?
With autorelease.
return [dateFromString autorelease];
See Memory management.
The problem I had was the format had CAP LETTERS for the YEAR.
This is correct:
[formatter setDateFormat:#"MM/dd/yyyy"];
And this is wrong: NOTE THE CAPS YYYY
[formatter
setDateFormat:#"MM-dd-YYYY"];

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

Object sent -autorelease too many times

I have this code that simple returns Today's date as a string formatted:
+(NSString*) getTodayString_YYYY_MM_DD {
NSDate * today = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
return [[formatter stringFromDate:today] autorelease];
}
With instruments I'm not getting a memory leak, but when I Analyze, XCode says:
Object sent -autorelease too many times
If I understand correctly, I have to release manually the formatter as I'm creating it using 'alloc', but I can't release here because I have to return the value, so I add the autorelease.
How I can do it better to improve it ?
thanks,
r.
You are -autoReleasing the NSString, not the formatter.
You don't need an autoRelease since -stringFromDate: is giving you an already autoReleased string.
Here is one way your code can look like:
+(NSString*) getTodayString_YYYY_MM_DD {
NSDate * today = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd"];
NSString *retString = [formatter stringFromDate:today];
[formatter release];
return retString;
}
Given that an NSDate's description is always in the format YYYY-MM-DD HH:MM:SS ±HHMM:
+ (NSString *) getTodayString_YYYY_MM_DD
{
return [[[NSDate date] description] substringToIndex:10];
}
Just throwing it out there. It's probably less efficient than the NSDateFormatter method.