NSDateFormatter and date conversion not working - objective-c

I am developing an app for the iPhone where I need to convert an date from an XML feed into just a HH:MM format.
I have the following method that doesn't work and I have no clue what I am doing wrong.
As an example, the timeToConvert string would be: "Mon, 01 Feb 2010 21:55:00 +0100" (without the quotes)
The method works when the region is set to US (I get back the correct date), but not when I change the region (in Settings->General->International) to Spain, or other regions (in that case I get back nil).
- (id)timeConvertToHHMM:(NSString *)timeToConvert {
NSString *newPubDate = timeToConvert;
//Let's remove any rubbish from the code
newPubDate = [newPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//create formatter and format to convert the XML string to an NSDate
NSDateFormatter *originalDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[originalDateFormatter setDateFormat:#"EEE, d MMM yyyy H:mm:ss z"];
//run the string through the formatter
NSDate *formattedDate = [[NSDate alloc] init];
formattedDate = [originalDateFormatter dateFromString:newPubDate];
//Let's now create another formatter to take the NSDate and convert format it to Hours and minutes
NSDateFormatter *newDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[newDateFormatter setDateFormat:#"HH:mm"]; // 24H clock set
// And let's convert it back to a readable string
NSString *calcHHMM = [newDateFormatter stringFromDate:formattedDate];
NSLog(#"CalcHHMM: %#", calcHHMM);
return calcHHMM;
}
Any hint on why this is not working, and just returning NULL will be more than welcome.

Problem appears to be your region setting is not "en-US" so the date formatter doesn't parse the string using the en-US format supplied. Although there may be a more elegant, general solution, doing a setLocale on originalDateFormatter to en_US can be used as a workaround to solve the problem.
As you've already tried in your code:
[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"] autorelease]];

I had the exact same issue. My problem was that my initial date string had a single millisecond character:
Example: 2011-02-06 08:13:22:1
and was being parsed with this format :[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
The iPhone simulator was forgiving and successfully parsed the date with the milliseconds, however when building to my iphone it did not.
Changing the formatter to: [formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss.S"]; solved the problem.

Related

Not getting NSDate from string

I have following date in string formate "date string : 2014-09-28 17:30:00"
Now, I want to convert it into NSDate.
I have use following code for this.
NSString *date = #"2014-09-28 17:30:00";
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
[dateFormatter1 setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter1 dateFromString:date];
NSLog(#"date from string: %#", dateFromString);
I got the following output.
date from string: 2014-09-28 12:00:00 +0000
So, Here Time is changed.
Please tell me, How can I convert into NSDate. What I am missing here?
When you pass an NSDate object into NSLog, it will print the NSDate in GMT time, which may not be your timezone (and why you were getting 12:00 instead of 17:30), this would also cause the output of your NSLog statement to be different for people who are running your code in different timezones, so what you want to do is call the [NSDateFormatter stringFromDate:] method if you want to keep your specified time from your date object:
So replace this line of code:
// Will print out GMT time by default (+0000)
NSLog(#"date from string: %#", dateFromString);
With this line:
// Will honor the timezone of your original NSDate object:
NSLog(#"date from string: %#", [dateFormatter1 stringFromDate:dateFromString]);
And that should print out the value you were hoping for.
// --------------------------//
Note: It is important to understand that NSDate objects do not have any concept of timezones, so it is up to the developer to manage and track their timezones with the provided platform methods.
On iOS, you can look into using this class:
NSTimeZone, which can help you manage/assign your timezone(s) on iOS platforms.
If you are developing for OSX, you can assign a timezone and locale with this method: -descriptionWithCalendarFormat:timeZone:locale:. (Sadly, this method is OSX-only)
Hope that helps.
There is a time zone component attached to your log at the end that means the date is converted to the specified time zone..here greenwhich mean time
So converting into your time locale can give you the right value you inserted
In your first string add +0000 to the end and check again you can see the value is the same you get.ie the conversion is done on the GMT format
visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html
This documentation provides you how to convert NSString to date.
this code is provided by apple documentation.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:162000];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(#"formattedDateString: %#", formattedDateString);
// Output for locale en_US: "formattedDateString: Jan 2, 2001".
To make string as date
NSString *formattedDateString = [dateFormatter stringFromDate:date];
stringFromDate:
Returns a string representation of a given date formatted using the receiver’s current settings.
what you had used
dateFromString:
Returns a date representation of a given string interpreted using the receiver’s current settings.

iOS create NSDate from output of Python datetime.isoformat()?

My python backend uses the isoformat() method on UTC date times, which results in strings that look like 2014-01-14T18:07:09.037000. Following other examples, I'm trying to create NSDates from those strings (passed up in JSON packets):
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:S"];
NSLog(#"cycle_base %#", myFields[#"cycle_base"]);
self.cycleBase = [dateFormatter dateFromString: myFields[#"cycle_base"]];
NSLog(#"cycleBase %#", self.cycleBase);
I've tried variants on the S part (which is supposed to be fractional seconds?) of the format string, but to no avail. I always get a nil back. What am I doing wrong?
iOS 7 follows the Unicode Technical Standard #35, which is a list of format patterns.
In this document you will find that the format string for fractional seconds is capitalized S.
NSString *string = #"2014-01-14T18:07:09.037000";
NSDateFormatter *formatter = [NSDateFormatter new];
formatter.dateFormat = #"yyyy-MM-dd'T'HH:mm:ss.S";
NSDate *date = [formatter dateFromString:string];
NSLog(#"%#", date);
This will net you a valid NSDate object. Don't forget to set the proper time zone and locale on your NSDateFormatter object.

Convert NSString in MM-dd-yy format to NSDate

In my application I am getting an NSString with the date as 01-22-12(MM-dd-yy). Now I want to convert that string into an NSDate. I used the code below. But it is giving the date as 2012-01-04 05:00:00 +0000
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yy"];
NSDate *dateFromString = [dateFormatter dateFromString:self.selectedWeek];
What is the proper way to convert my string to an NSDate?
From your original question I'm not totally clear whether you want:
1 the string as an NSDate.
or
2 to be able to get the original date NSString back out of an NSDate instance.
Your code is basically right. I just ran a slightly adapted version of it, which seemed to work fine:
NSString *dateString = #"01-22-12";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM-dd-yy"];
NSDate *date = [dateFormatter dateFromString:dateString];
NSString *outString = [dateFormatter stringFromDate:date];
NSLog(#"%#",date);
NSLog(#"%#",outString);
This produced:
2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 2012-01-22 00:00:00 +0000
2013-02-24 09:57:24.352 datesAgain.m.out[787:707] 01-22-12
So, either way the result seems to be what you were looking for. I suspect that the reason you are getting an incorrect value is that self.selectedWeek doesn't have the value you think it does. I'd inspect it, either in the debugger or with NSLog. If you are creating it somewhere else using another format string, be aware that they can be tricky and slightly unintuitive - for instance s means seconds, but S means fractions of a second.
Documentation available here - most recent Unicode formatting standard here (ios6.0/OSX 10.8) - also linked to in previous link, as are all previous relevant standards
you can use descriptionWithCalendarFormat:timeZone:locale:
NSString * mydate = [dateFromString descriptionWithCalendarFormat:#"%Y-%m-%d"
timezone:nil
locale:nil];

nsformatter dateFromString is nil

Im working on iphone app using xcode,objective c and targeting ios 5 minimum.
All I am trying to do is convert a string to a date. I have read lots on this and it should be a simple straight forward task. I have seen many other questions like this in forum but what is working for people doesnt seem to be working for me.
Here is what I am doing
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = [dict valueForKey:#"DateOfBirth"];
NSDate *dobDate = [dateFormatter dateFromString:dobText];
the dobText is always in format #"1999-01-01" which matches the date format set in the date formatter but the result when using date from string is always nil.
can anyone explain this to me and let me know how to fix it?
Look at the user preferences on your device. The documentation says:
Note that although setting a format string (setDateFormat:) in
principle specifies an exact format, in practice it may nevertheless
also be overridden by a user’s preferences—see Data Formatting Guide
for more details.
are you sure the date is using a - and not a – in the data you get from the dict. As i can reproduce a nil result when i use a – (alt + -)
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = #"2009-02-12";
NSDate *dobDate = [dateFormatter dateFromString:dobText];
NSLog(#"%#", dobDate);
Try doing this, will likely fix your problem.
NSString *dobText = [[dict valueForKey:#"DateOfBirth"] stringByReplacingOccurrencesOfString:#"—" withString:#"-"];
I suspect like bigkm say, your dashes may be getting in the way.
I would suggest you try a dummy string in line first. e.g.
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSString *dobText = #"1999-01-01" // [dict valueForKey:#"DateOfBirth"];
NSDate *dobDate = [dateFormatter dateFromString:dobText];
Now does that work? It should. Now triangulate another way:
Remove the dashes completely from the dob text, so that it has the format 'yyyyMMdd'
Have the date formatter look for this same format
Does that work? It should. And that would prove that the separator characters in your format are the issue and need some further inspection (or cleansing as bigkm suggested).
Side node re threading: NSDateFormatter is fine if you use it on the thread on which it was created. If you don't, you'll know b/c the app will crash.
If your date format is correct, I can suggest to set NSLocale to your NSDateFormatter.
For me this code works on simulator:
NSString *format = [NSString stringWithFormat:#"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:format];
NSDate *date = [df dateFromString:pubDateSttring];
but on the device date is always NIL.
I've found workaround of setting NSLocale:
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];

How do I convert from NSString to NSDate using NSDateFormater

I have this string: 2012-01-12T21:01:00 and this code:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss a"];
NSDate* arrivalTime=[df dateFromString:field_arrival_time];
But it returns nil. What date format should I use to parse this string?
Your string 2012-01-12T21:01:00 contains the literal T (At least I believe it's a literal, it doesn't appear to signify a timezone). You must include this in your date format.
[df setDateFormat:#"yyyy-MM-dd'T'hh:mm:ss"];
Note the lack of the a in the date format, using it will require your input string to use AM or PM preceded by a white space. For more information on special characters with NSDateFormatter take a look at the Date Formatting Guide paying extra attention to the Fixed Formats.
Edit: Your input string does not specify a timezone, it will probably be interpreted as UTC and be localized to the timezone of your machine when you output it through NSLog().
I have tried a lot on your string but never get result. only nil shows on console. but when i remove character "T" from your string it gives perfect result.
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2012-01-12 21:01:00"];
NSLog(#"date %#", date);
NSDateFormatter *f2 = [[NSDateFormatter alloc] init];
[f2 setDateFormat:#"dd-MM-yyyy"];
NSString *s = [f2 stringFromDate:date];
NSLog(#"S %#", s);
/// OutPut : S 12-01-2012