depicus

changing the digital world one bit at a time...

Blants (noun) the rants of a blogger

iDev – Getting a good looking date with prefix

August 5, 2010 by The Man

Not sure it should take this much code but….

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MMMM yyyy"];
    
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"HH:mm"];
    
    NSDateFormatter *dayFormat = [[NSDateFormatter alloc] init];
    [dayFormat setDateFormat:@"d"];
    
    NSDate *now = [[NSDate alloc] init];
    
    NSString *theDate = [dateFormat stringFromDate:now];
    NSString *theTime = [timeFormat stringFromDate:now];
    NSString *theDay = [dayFormat stringFromDate:now];
    
    NSString *dayWithPrefix;
    
    if ((theDay == @"1") || (theDay == @"21") || (theDay == @"31"))
    {
        dayWithPrefix = [NSString stringWithFormat:@"%@st", theDay];
    }
    else if ((theDay == @"2") || (theDay == @"22"))
    {
        dayWithPrefix = [NSString stringWithFormat:@"%@nd", theDay];
    }
    else if ((theDay == @"3") || (theDay == @"23"))
    {
        dayWithPrefix = [NSString stringWithFormat:@"%@rd", theDay];
    }
    else
    {
        dayWithPrefix = [NSString stringWithFormat:@"%@th", theDay];
    }
    
    
    [lblDateTime setText:[NSString stringWithFormat:@"Date: %@ %@ Time: %@", dayWithPrefix, theDate, theTime]];

    [dateFormat release];
    [timeFormat release];
    [theDay release];
    [now release];