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"];
Related
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];
I'm passing a string from javascript to Objective-C in the form of "2012-02-17 14:21:30 +0000".
My code is as follows:
NSString *firingDate = [_parameters objectForKey:#"fire"];
NSDate *notificationDate = [NSDate dateWithString:firingDate];
The issue is that I ended up reading the OS X reference instead of the iOS docs (doh!) so this throws a warning as dateWithString isn't present in iOS. In theory I suppose that this shouldn't work at all but it does, albeit with that warning.
What is the Correct way to convert the string to a NSDate?
The correct way is to use NSDateFormatter as a factory to create dates from strings (and vice versa).
Try:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = #"YYYY-MM-dd HH:mm:ss Z";
NSDate *notificationDate = [formatter dateFromString:firingDate];
Try this:
NSString *firingDate = [_parameters objectForKey:#"fire"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *notificationDate = [dateFormatter dateFromString:firingDate];
Check out the reference for parsing dates from multiple regions.
Don't forget to release your formatter when finished.
Ive been racking my brains with no luck. Could someone please tell me how i would convert this string:
"2011-01-13T17:00:00+11:00"
into a NSDate?
The unicode date format doc is here
Also, for your situation, you could try this:
// original string
NSString *str = [NSString stringWithFormat:#"2011-01-13T17:00:00+11:00"];
// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// ignore +11 and use timezone name instead of seconds from gmt
[dateFormat setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss'+11:00'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Melbourne"]];
NSDate *dte = [dateFormat dateFromString:str];
NSLog(#"Date: %#", dte);
// back to string
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:#"YYYY-MM-dd'T'HH:mm:ssZZZ"];
[dateFormat2 setTimeZone:[NSTimeZone timeZoneWithName:#"Australia/Melbourne"]];
NSString *dateString = [dateFormat2 stringFromDate:dte];
NSLog(#"DateString: %#", dateString);
[dateFormat release];
[dateFormat2 release];
Hope this helps.
put the T part in single quotes, and check the unicode docs for the exact formatting. In my case, I have something similar, which I do this:
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"YYYY-MM-dd'T'HH:mm:ss.SSS"];
Again, not exactly the same, but you get the idea. Also, be careful of the timezones when converting back and forth between strings and nsdates.
Again, in my case, I use:
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:#"America/New_York"]];
Did you try this
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *dateT = [dateFormatter dateFromString:str];
Cheers
You might check out TouchTime.
https://github.com/jheising/TouchTime.
It's a direct port of the awesome strtotime function in PHP in 5.4 for Cocoa and iOS. It will take in pretty much any arbitrary format of date or time string and convert it to an NSDate.
Hope it works, and enjoy!
Try using this cocoapods enabled project. There are many added functions that will probably be needed as well.
"A category to extend Cocoa's NSDate class with some convenience functions."
https://github.com/billymeltdown/nsdate-helper
Here's an example from their page:
NSDate *date = [NSDate dateFromString:#"2009-03-01 12:15:23"];
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.
I have a countdown timer which countsdown from the current date/time to a specific future date/time. It is working great except for one problem. I input the future date using NSDateFormatter and dateFromString. It doesn't seem to be able to accept any time (hour) over 12 though indicating it is not support 24 hour clock. Is there a way to enable 24 hour clock support or a workaround? Here is some of my code:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *myDate = [df dateFromString:#"2010-03-14 15:00:00"];
NSDateFormatter follows the Unicode standard for date and time patterns. Use 'H' for the hour on a 24-hour clock:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *myDate = [df dateFromString:#"2010-03-14 15:00:00"];
I had the same problem and using HH worked only on some devices, like Roger also verified. In the end this was the solution that worked for me, I hope it works for others. Finding this answer was difficult, there are no forums with it, it was literally trial and error following the apple documentation.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"];
[dateFormatter setLocale:enUSPOSIXLocale];
NSString *dateFormat = #"dd/MM/yyyy HH:mm"; //MM for month, mm for minutes
[dateFormatter setDateFormat:dateFormat];
[dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
date = [dateFormatter dateFromString:string];
My solution on Swift:
let formatter = NSDateFormatter()
var defIdentifer = formatter.locale.localeIdentifier
if !defIdentifer.hasSuffix("_POSIX") {
defIdentifer = defIdentifer+"_POSIX"
let locale = NSLocale(localeIdentifier: defIdentifer)
formatter.locale = locale
}
formatter.dateFormat = "HH:mm"
I had a similar problem recently, instead of HH, NSDateFormatter ignored hh, a(AM/PM Symbol) and G (cyclic era name) in my app.
And I was surprised to find that if I go to localization setting of my device and make some random choice, all the freaks are gone and the error cannot be produced again. Very weird.
Then I tested on simulator to do some study on it. There is my solution:
After you created the NSDateFormatter, explicitly set the locale property even you are using current locale, more importantly, DON'T use [NSLocale currentLocale], this one is bugged and can be somehow "overriden" by user setting, use systemLocale or explicitly create an NSLocale instance using a locale identifer.
Taken from the Apple Technical Q&A on NSDateFormatters
Q: I'm using NSDateFormatter to parse an Internet-style date, but this fails for some users in some regions. I've set a specific date format string; shouldn't that force NSDateFormatter to work independently of the user's region settings?
A: No. While setting a date format string will appear to work for most users, it's not the right solution to this problem. There are many places where format strings behave in unexpected ways.
This is how I have done mine in Swift:
private let dateFormatter: NSDateFormatter = {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone.init(forSecondsFromGMT: 0)
return dateFormatter
}()
Objective C version of getting NSDate from 24-hour string when user has set 12 hour format on their iPhone without changing locale and setting timezone:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *localeId = dateFormatter.locale.localeIdentifier;
if (! [localeId hasSuffix:#"_POSIX"]) {
localeId = [localeId stringByAppendingString:#"_POSIX"];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:localeId];
}
dateFormatter.dateFormat = #"yyyy-MM-dd'T'HH.mm.ss";
NSDate *date = [dateFormatter dateFromString:dateText];