NSDateFormatter extract time from date string
I hacked together the ugly little C monster below.
You'll probably the find NSDate class +dateWithNaturalLanguageString method's very easy to use http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html
However I agree with K that you should look at the classes that Apple provide for this purpose - they are rather elegant. I used them 2 or 3 years to handle dates in the file system.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define number(c) (('0'<=*c)&&(*c<='9'))
#define lengthof(x) sizeof(x)/sizeof(x[0])
int main(int argc, char* argv)
{
const char* t = "8/6/2010 12:30:00 PM.";
int date[5] ;
const char* c = t ;
for ( int i = 0 ; i < lengthof(date) ; i++ ) {
// printf("i = %d c = %s\n",i,c);
date[i]=atoi(c) ;
while ( number(c) ) c++ ;
while ( !number(c) ) c++ ;
}
printf("h,m = %d %d\n",date[3],date[4]) ;
return 0 ;
}
Here's another extensive effort that uses three methods:
1) The unspeakably dangerous, but frequently used sscanf of the std C library
2) A variant of my earlier hack (with good() thrown in for safety)
3) Using NSDateComponents to get the hours and minutes.
- and I'm sure there are as many solutions as there are programmers!
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(int argc, char* argv)
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
const char* t = "8/6/2010 12:30:00 PM.";
// stupid and dangerous
int month,day,year,hour,minute;
sscanf(t,"%d/%d/%d %d:%d",&month,&day,&year,&hour,&minute) ;
printf("h,m = %d %d\n",hour,minute) ;
// complicated - however its quite clever
#define number(c) (('0'<=*c)&&(*c<='9'))
#define lengthof(x) sizeof(x)/sizeof(x[0])
#define good(c) (*c)
int date[5] ;
const char* c = t ;
for ( int i = 0 ; good(c) && i < lengthof(date) ; i++ ) {
// printf("i = %d c = %s\n",i,c);
date[i]=atoi(c) ;
while ( good(c) && number(c) ) c++ ;
while ( good(c) && !number(c) ) c++ ;
}
if ( good(c) ) printf("h,m = %d %d\n",date[3],date[4]) ;
// sensible
NSString* T = [NSString stringWithUTF8String:t] ;
NSDate* D = [NSDate dateWithNaturalLanguageString:T] ;
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* comps = [gregorian components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:D
];
printf("h,m = %d %d",(int)[comps hour],(int)[comps minute]);
[pool drain];
return 0;
}