NSDateFormatter does return what is expected - iphone

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

Related

NSString compare is throwing exception SIGABT

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.

iphone - How to convert rfc3399 formated date string to NSDate object?

I am getting the rfc3399 formatted date string through google calender web services. I want to convert this string into NSDate object so that I can add an event about this to the local calendar. I found the below method in Apple's documentation regarding NSDateFormatter , but its not working
Date String - 2012-05-23T18:30:00.000-05:00
- (NSString *)userVisibleDateTimeStringForRFC3339DateTimeString:(NSString *)rfc3339DateTimeString {
/*
Returns a user-visible date time string that corresponds to the specified
RFC 3339 date time string. Note that this does not handle all possible
RFC 3339 date time strings, just one of the most common styles.
*/
NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
// Convert the RFC 3339 date time string to an NSDate.
NSDate *date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
NSString *userVisibleDateTimeString;
if (date != nil) {
// Convert the date object to a user-visible date string.
NSDateFormatter *userVisibleDateFormatter = [[NSDateFormatter alloc] init];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
return userVisibleDateTimeString;
}
Please help me , I have tried changing the date format quite a lot times but no success.
try with this method..
-(NSDate *)convertStringToDate:(NSString *) date {
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:#"YYYY-MM-DD'T'HH:mm:ssZ"];// set format here which format in string date
/// also try this format #"yyyy-MM-dd'T'HH:mm:ss.fffK"
date = [date stringByReplacingOccurrencesOfString:#"+0000" withString:#""];
nowDate = [formatter dateFromString:date];
// NSLog(#"date============================>>>>>>>>>>>>>>> : %#", nowDate);
return nowDate;
}
call this method like bellow..
NSDate *date = [self convertStringToDate:rfc3339DateTimeString];
also for try with some rfc Date formate with fffK for this format see this bellow. link..
how-do-i-parse-and-convert-datetimes-to-the-rfc-3339-date-time-format
i hope this answer is helpful
The issue is the date contains (-05:00 )':' in the timezone value ... you have to remove it from the string then the above method will work fine......The new date string should look like below
2012-05-23T18:30:00.000-0500 - This should be the right format .

Not able to convert date from string

I am doing an application where I am using the following link http://iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html to convert the date from string.
I am using below code to same by following above tutorial link. when I NSlog PresentDateTime it gives 20120111 13:03:49.263+05:30.
so I am taking this format and want to convert into the format of "EEEE MMMM d, YYYY h:mm a, zzz".
To do so when I assign the same to the variable
NSString *today = presentDateTime;
when I NSLog Datestring I am getting result NULL can I know where I am going wrong? please help me to solve this issue by suggesting what changes to be done
//code
-(NSString *)DateFormat:(NSString *) presentDateTime
{
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#"T" withString:#" "];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#" +" withString:#"+"];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:#"-" withString:#""];
NSLog(#"Present date::::%#",presentDateTime);
NSString *today = presentDateTime;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMdd HH:mm:ss:SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
[dateFormat setDateFormat:#"EEEE MMMM d, YYYY h:mm a, zzz"];
NSString *dateString = [dateFormat stringFromDate:date];
[dateFormat release];
NSLog(#"dateString:::Date>>>>:%#::::\n%#",dateString, presentDateTime);
return dateString;
Your date format pattern for parsing the date is wrong/incomplete. For the string 20120111 13:03:49.263+05:30 the format would be YYYYMMdd HH:mm:ss.SSSZZZ. See this table for the format string patterns.
Edit: After playing around with the code, it turns out that the NSDateParser chokes on the timezone +05:30. It expects +0530, without the colon. Here's how to remove it:
NSString *today = #"20120111 13:03:49.263+05:30";
NSRange colon = [today rangeOfString:#":" options:NSBackwardsSearch];
if (colon.location != NSNotFound) {
today = [today stringByReplacingCharactersInRange:colon withString:#""];
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYYMMdd HH:mm:ss.SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
NSLog(#"%#", date);
When you parse your original date string you need to specify the entire format, like this:
[dateFormat setDateFormat:#"yyyyMMdd HH:mm:ss.SSSZZZ"]
Compare your code with the following
NSString *dateString = #"6:30 18 Oct";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm dd/MMM"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release];
Its just sample to follow. and figure out what is going wrong by printing it in nslog.
Your date variable is always nil because your date format (yyyyMMdd) is incomplete as your input string today contains extra information (20120111 13:03:49.263+05:30). So you can just crop unnecessary characters:
if ([presentDateTime count] < 8) return nil;
NSString *today = [presentDateTime substringToIndex:8];
Or you should specify full date format as mentioned by #jonkroll

How to format a date from yyyy-MM-dd to dd.MM.yyyy

I have a string with this data:
2011-09-13 22:20:00
I want to have this data:
13.09.2011
Additional I want to have the string "Today" when the date is today.
How to do this in Objective C?
I tried it the last 1 hour, but don't get it:
//Date basteln
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd"];
NSString* str = [[ens objectForKey:#"datum_server"] substringToIndex:10];
NSLog(#"%#", str);
NSDate *now = [dateFormat dateFromString:str];
NSLog(#"%#", now);
[dateFormat setDateFormat:#"dd.MM.yyyy"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
[now release];
So I tried to cut of the time, convert it with the wrong format to the right format.
But it crashed in a SIGBART.
Ideas?
Don't release
now
This is an autoreleased object, you are over releasing it and this is causing your crash.
You should always release those object which you own it by using 'init', 'copy' 'alloc', 'new', 'copy', or 'mutableCopy'. so there you do not need to release the date object because you did not own that.

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.