NSDateFormatter producing (null) SQLite and iOS 5.1 - objective-c

Maybe somebody can help explain why I am getting a null value when converting a string to a date. It all looks right but I'm obviously missing something here.
Some background:
This iPad app will be used in different countries and I will need to do a calculation on the date to see if 90 days have passed since a user last logged in.
I have a SQLite Database with a DateLastIn field set as TEXT
My Object has a DateLastIn property set as NSDate
When populating my record object I set up a NSDateFormatter as such..
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"]; // SQLite default date format
Then I read in the DateLastIn (Using FMDB wrapper for SQLite).
// test SQLite as String
NSString *testDate = [results stringForColumn:#"DateLastIn"];
NSLog(#"DateLastIn straight from DB (string) shows %#", testDate);
Result:
DateLastIn straight from DB (string) shows 2012-04-23 18:20:51
All is good so far. Next I test converting this to an NSDate object e.g
NSDate *aDate = [[NSDate alloc] init];
aDate = [formatter dateFromString:testDate];
NSLog(#"Using formmater on string date results in: %#", aDate);
Result:
Using formmater on string date results in: (null)
I have tried DATETIME in SQLite, I've tried using NSString in my object instead of NSDate and seem to be going around in circles.
Any help much appreciated.

NSDateFormatter uses the format patterns from the Unicode Technical Standard #35.
For the hour format, you need HH (Hour [0-23]) not hh (Hour [1-12]).

I changed your date format to HH not hh and it works. Here is my test code....
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"]; // SQLite default date format
// test SQLite as String
NSString *testDate = #"2012-04-23 18:20:51";
NSDate *aDate = [formatter dateFromString:testDate];
NSLog(#"Using formmater on string date results in: %#", aDate);

Related

How can I handle this European-style timestamp?

I’m trying to check through thousands of lines in video subtitle files (in .srt format) and searched the internet for days on end for a solution, but to no avail. The subs contain in/out timestamps as shown in the following example:
61
00:08:35,504 --> 00:08:38,629
Do you know where he left the car keys?
in hours, minutes, seconds and milliseconds (notice the European-style comma before the millisecond part, representing the decimal point). What I plan to do is parse the timestamp into its two components and check the difference between them, since many are faulty. I built a simple test function to handle the plain hh:mm:ss part which works well:
-(IBAction)checkSubLength:(id)sender
{
NSString *inStr = #"10:10:45";
NSString *outStr = #"10:20:57";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss"];
NSDate *inTime = [dateFormatter dateFromString:inStr];
NSDate *outTime = [dateFormatter dateFromString:outStr];
NSTimeInterval distanceBetweenDates = [outTime timeIntervalSinceDate:inTime];
NSLog(#"time difference:%.3f", distanceBetweenDates);
}
However, I just can’t get the fractional part to display no matter what I try. How can I modify/change my code do that? Any help much appreciated.
You need to specify the millis in the format string:
NSString *inStr = #"10:10:45,111";
NSString *outStr = #"10:20:57,222";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm:ss,SSS"];
NSDate *inTime = [dateFormatter dateFromString:inStr];
NSDate *outTime = [dateFormatter dateFromString:outStr];
NSTimeInterval distanceBetweenDates = [outTime timeIntervalSinceDate:inTime];
NSLog(#"time difference:%.3f", distanceBetweenDates);
which then prints
time difference:612.111
as expected

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