tags:

views:

151

answers:

2

Hello,

Can someone help me out with something.

I'm trying to get the current part of the day, am or pm. Is there an easy way of accomplishing this?

Thanks.

+6  A: 

Sure, use NSDateFormatter:

NSDate *now = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat: @"a"];

NSLog ([formatter stringFromDate: now]);

[formatter release];

Outputs:

2009-08-06 14:20:35.538 yourApp [4971:20b] PM

Jacob H. Hansen
A: 

Maybe there is an easier way .. but this works.

    NSDate *now=[NSDate date];
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:NSHourCalendarUnit fromDate:now];
    int hour = [components hour];
    if ( hour > 12 ){
     NSLog(@"PM %d",hour);
    } else {
     NSLog(@"AM");
    }
Ira Cooke
Oops. A bit slow. Jacob's method is probably cleaner.
Ira Cooke