Problem converting Ruby on Rails DateTime to NSDate
Why is this ...
NSString *mydate = @"2011-07-20T23:59:00-07:00"
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSLog开发者_如何学JAVA(@"%@", [[dateFormatter dateFromString:mydate] description]);
... returning "(null)" in the console?
Your date format of @"yyyy-MM-dd'T'HH:mm:ss'Z'"
means that it's looking for a literal "Z
" character at the end of the string. However, your string is:
@"2011-07-20T23:59:00-07:00"
I don't see a "Z
" there, do you? Thus, the date comes back as nil
because your string does not match the format specified.
According to the Date Formatting Patterns documentation, you're probably looking for the format string of:
@"yyyy-MM-dd'T'HH:mm:ssZZ"
However, even that might not work, because if you notice your source string has a colon (":
") in between the hours and minutes of the timezone offset. There's no timezone specifier that accounts for that. If that is indeed the format in which ROR is returning the date, then ROR is wrong.
I am doing transfer of Dates from Ruby to iOS via a JSON API and I believe I have read the same article.
http://www.cimgf.com/2012/05/29/importing-data-made-easy/
I am almost positive that they have mistakenly added the 'Z' as a string literal
-
To get Ruby to output as you are probably expecting I did the following:
1.9.3-p392 :012 > s = Time.now
=> 2013-05-03 15:47:51 +0100
1.9.3-p392 :013 > s.strftime("%Y-%m-%d\T%H:%M:%S%:z")
=> "2013-05-03T15:47:51+01:00"
Notice the %:z that is available in Ruby 1.9.3 at least
Is there a Ruby 1.8.7 time.strftime %z bug?
精彩评论