Creating NSDate from NSString - iphone

I have the following NSString:
NSString * dateString = #"2012-01-24T14:59:01Z";
I want to create an NSDate from that string. I looked up the NSDate Class Reference and thought of using dateWithNaturalLanguageString::
Creates and returns an NSDate object set to the date and time
specified by a given string.
+ (id)dateWithNaturalLanguageString:(NSString *)string
Parameters
string
A string that contains a colloquial specification of a date,
such as “last Tuesday at dinner,” “3pm December 31, 2001,” “12/31/01,”
or “31/12/01.”
Return Value
A new NSDate object set to the current
date and time specified by string.
However, when I'm trying to use it like this:
NSDate * date = [NSDate dateWithNaturalLanguageString:dateString];
I'm getting the following error:
No known class method for selector 'dateWithNaturalLanguageString:'

NSDateFormatter class will help you with this problem. And there are many questions about this already, for example, here is the first one: Convert NSString->NSDate?
http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSDateFormatter_Class/Reference/Reference.html

Try using the constructor dateWithString constructor or (if that gives you a similar error), try using an NSDateFormatter as described here.

The dateWithNaturalLanguageString: class method is only implemented on Mac OS X, not on iOS, that is why you're getting the error.
To achieve what you're looking for, you need the NSDateFormatter class. The class is quite heavy, so you'll want to read the documentation first to understand how best to use it.

Found exactly what I was looking for here. It's an RFC 3339 date-time.
- (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.
{
NSString * userVisibleDateTimeString;
NSDateFormatter * rfc3339DateFormatter;
NSLocale * enUSPOSIXLocale;
NSDate * date;
NSDateFormatter * userVisibleDateFormatter;
userVisibleDateTimeString = nil;
// Convert the RFC 3339 date time string to an NSDate.
rfc3339DateFormatter = [[[NSDateFormatter alloc] init] autorelease];
enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"] autorelease];
[rfc3339DateFormatter setLocale:enUSPOSIXLocale];
[rfc3339DateFormatter setDateFormat:#"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
[rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
date = [rfc3339DateFormatter dateFromString:rfc3339DateTimeString];
if (date != nil) {
// Convert the NSDate to a user-visible date string.
userVisibleDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
assert(userVisibleDateFormatter != nil);
[userVisibleDateFormatter setDateStyle:NSDateFormatterShortStyle];
[userVisibleDateFormatter setTimeStyle:NSDateFormatterShortStyle];
userVisibleDateTimeString = [userVisibleDateFormatter stringFromDate:date];
}
return userVisibleDateTimeString;
}

Related

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 .

Convert integer to a date string

In Objective-C: Is there a simple way, as in Excel and SAS, to convert an integer into a datetime string?
In Excel, you'd format to "mmm dd, yyyy hh:mm:ss".
For instance, if I had the integer:
1328062560
and I want the output to be:
2012-01-31 21:16:00
or even (as in Excel):
Jan 31, 2012 21:16:00
PS: I don't want to be too demanding, but I'd like it simple and inline for use in NSLog, so I can write simply for debugging
NSLog("The time as an integer is %d and as a date %mmmddyyyyhh:mm:ss", [array objectAtIndex: i], [array objectAtIndex: i]);
You can get an NSDate object like this:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:1328062560];
Then, if you don't care about the exact format of the string, you can just do this:
NSString *s = [date description];
That will give you a string like “2012-02-01 02:16:00 +0000”.
If you want a specific string format, use an NSDateFormatter.
You can use NSDateFormatter to do this. You first make a string from your integer value:
NSString *dateString = [NSString stringWithFormat:#"%d", integerDate];
And then create an NSDateFormatter with the corresponding format:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[myDateFormatter setDateFormat:#"yyyyMMddhhmm"]; // Change to suit your format
NSDate *dateFromString = [myDateFormatter dateFromString:dateString];
You can then retrieve the date as a string in the format you want:
[myDateFormatter setDateFormat:#"yyyy/MM/dd hh:mm"]; // Change to suit your format
NSString *stringFromDate = [formatter stringFromDate:dateFromString];
Assuming that integer is a time in seconds since the epoch, you can use NSDate's initWithTimeIntervalSince1970 or dateWithTimeIntervalSince1970 methods to create an NSDate object with the date you care about, and then use NSDateFormatter to pretty it up for display.

Converting Adobe PDF date String to NSDate

The input string is '20100908041312'
the format is year,month,day,Hours,minutes,seconds,time zone
and I have ben trying to convert it to an NSDate with this: #"yyyyMMddHHmmsszz"
But NSDate is nil, anyone see what I'm doing wrong?
-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{
//20100908041312
//year month day Hours minutes seconds and time zone
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyyMMddHHmmsszz"];
NSDate *date = [dateFormat dateFromString:_string];
//date is nil...
[dateFormat release];
return date;
}
EDIT: its the time zone breaking it
EDIT2: #"yyyyMMddHHmmssTZD" stops it returning nil, but dosnt pick the time zone correctly
EDIT3: This was the code I Used in the end...i found that the format changes from PDF to PDF so the code deals with the variations that i Found, in some cases this wont extract the Time Zone Properly.
-(NSDate*)convertPDFDateStringAsDate:(NSString*) _string{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSString * formatCheck = [_string substringToIndex:2];
if(![formatCheck isEqualToString:#"D:"])
{
NSLog(#"ERROR: Date String wasnt in expected format");
return nil;//return [NSDate date];
}
NSString * extract = [_string substringFromIndex:2];
//NSLog(#"DATESTRING:'%#'",extract);NSLog(#"DATELENGTH:%i",[extract length]);
if([extract length]>14)
{
[dateFormat setDateFormat:#"yyyyMMddHHmmssTZD"];
}
else
{
[dateFormat setDateFormat:#"yyyyMMddHHmmss"];
}
NSDate * date = [dateFormat dateFromString:extract];
[dateFormat release];
return date ;
}
It should follow the unicode standard for the setDateFormat: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
You should be able to set the timezone this way:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyyMMddHHmmss"];
//Optionally for time zone conversations
[formatter setTimeZone:[NSTimeZone timeZoneWithName:#"..."]];
Alex
I recognize the posting is over a year old, but no time is too late for a better answer.
Since you specify the input string is an Adobe PDF date string, then the format should conform to the PDF specification, which per the spec is: YYYYMMDDHHmmSSOHH'mm (omitting the prefix D:).
Note your input string is 14 characters long and your NSDate format is 16 characters long, so the timezone isn't in your input string as stated.
Nonetheless, the real answer to your question is to use the Quartz 2D CGPDFString function:
CFDateRef CGPDFStringCopyDate (CGPDFStringRef string
);
The function returns a CFDateRef which has a toll-free bridge to NSDate, so you can pass the date read from a PDF to this function and easily get back an NSDate by casting.
"12" isn't a valid time zone for any of the Unicode date format patterns, so NSDateFormatter returns nothing. http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
You may have to use all but the last two digits, then set the time zone on your new NSDate object by translating Adobe's two-digit number to an appropriate time zone.

Converting ex. 2010-09-11T00:00:00+01:00 format to NSDate

I have spent way too much time (over an hour) on what I though would be a two minute task.
On the iPhone:
NSString * dateString = #"2010-09-11T00:00:00+01:00";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssTZD"];
NSDate *date = [formatter dateFromString:dateString];
RESULT: date == nil
What am I missing!! (Besides my deadline)
Regards,
Ken
TZD isn't a defined formatter per the unicode spec. The document you've linked to elsewhere was a suggestion someone made to W3C, for discussion only. The unicode standard followed by Apple is a finished standard, from a different body.
The closest thing to what you want would be ZZZ (ie, #"YYYY-MM-dd'T'HH:mm:ssZZZ"), but that doesn't have a colon in the middle. So you'd need to use the string:
2010-09-11T00:00:00+0100
Rather than the one you currently have that ends in +01:00.
E.g. the following:
NSString * dateString = #"2010-09-11T00:00:00+0100";
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [formatter dateFromString:dateString];
NSLog(#"%#", date);
Logs a valid date object, of 2010-09-10 23:00:00 GMT.
Tip: try using your formatter to convert from an NSDate object to a string, then see what you get. It's often easier to debug in that direction than the other.
Have you read this?
http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns
That TZD at the end of your format string looks a bit dodgy.
I solved this issue using this code.

iPhone, if I'm converting a date string from one format to another, to store it, do I have to convert it to a date, how?

I need to show a date in a certain format on screen, but I need to store the date as a string in another format. I think this means I have to convert it to a date and back to a string.
How do i do this ?
I have already figured out how to convert my string to a date, however build analyser gives me a warning.
I want to convert the string from dd MM yyyy to yyyy-MM-dd
He my code so far...
NSString *startDateString = btnStartDate.titleLabel.text;
NSDateFormatter *dateStartFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateStartFormatter setDateFormat:#"dd MM yyyy"];
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];
The analyzer warns you of a leak. First, you assign a new object to datStartDate, and then you store a new value with datStartDate = [dateStartFormatter dateFromString:startDateString]; without releasing the previous object first.
So instead of:
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];
You should just write:
NSDate *datStartDate = [dateStartFormatter dateFromString:startDateString];
Well you're allocating space for datStartDate for a new NSDate, then replacing it with a completely new NSDate from your date formater (now you have memory set aside for the first NSDate that is never going to be used)
Use this:
NSDate* datStartDate = [dateStartFormater dateFromString:startDateString];
then use your dateStartFormater or another NSDateFormatter to turn your date into the required string like so:
[dateStartFormatter setDateFormat:#"yyyy MM dd"];
NSString* formatedDate = [dateStartFormater stringFromDate:datStartDate];