Permalink
Browse files

adding convenience methods to read rails' string dates into NSDate ob…

…jects in FMResultSet
  • Loading branch information...
1 parent 09e2378 commit 8a5f5c5f5ef888dc1917b0edbcf8cfc56a0b549d @coryosborn coryosborn committed Dec 20, 2011
Showing with 37 additions and 1 deletion.
  1. +3 −0 src/FMResultSet.h
  2. +34 −1 src/FMResultSet.m
View
@@ -68,6 +68,9 @@
- (NSDate*)dateForColumn:(NSString*)columnName;
- (NSDate*)dateForColumnIndex:(int)columnIdx;
+- (NSDate*)railsDateForColumn:(NSString*)columnName;
+- (NSDate*)railsDateForColumnIndex:(int)columnIdx;
+
- (NSData*)dataForColumn:(NSString*)columnName;
- (NSData*)dataForColumnIndex:(int)columnIdx;
View
@@ -279,11 +279,44 @@ - (NSDate*)dateForColumnIndex:(int)columnIdx {
if (sqlite3_column_type(statement.statement, columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
return nil;
}
-
+
return [NSDate dateWithTimeIntervalSince1970:[self doubleForColumnIndex:columnIdx]];
}
+- (NSDate*)railsDateForColumn:(NSString*)columnName {
+ return [self railsDateForColumnIndex:[self columnIndexForName:columnName]];
+}
+
+static NSDateFormatter *railsDateFormatter;
+
+- (NSDate*)railsDateForColumnIndex:(int)columnIdx {
+
+ if (sqlite3_column_type(statement.statement, columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
+ return nil;
+ }
+
+ // Rails dates are returned as a String in the format yyyy-MM-dd HH:mm:ss.sssss
+ NSString *dtString = [self stringForColumnIndex:columnIdx];
+ NSString *millis = nil;
+ // parse out the milliseconds portion
+ NSRange decRng = [dtString rangeOfString:@"."];
+ if (decRng.location != NSNotFound) {
+ millis = [NSString stringWithFormat:@"0%@", [dtString substringFromIndex:decRng.location]]; // becomes 0.xxxx seconds
+ dtString = [dtString substringToIndex:decRng.location];
+ }
+
+ if (!railsDateFormatter) {
+ railsDateFormatter = [[NSDateFormatter alloc] init];
+ railsDateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
+ }
+ NSDate *dt = [railsDateFormatter dateFromString:dtString];
+ if (millis)
+ dt = [dt dateByAddingTimeInterval:[millis doubleValue]];
+ return dt;
+}
+
+
- (NSData*)dataForColumn:(NSString*)columnName {
return [self dataForColumnIndex:[self columnIndexForName:columnName]];
}

0 comments on commit 8a5f5c5

Please sign in to comment.