Return to WrightsCS.com   |   Check out WrightsCSApps.com   |   How to Post Snippets  

Not registered? Thats okay! You can Submit a Snippet without being a member of this site!


*****1vote

I’ve found myself needing to get the time and date (formatted) quickly, so I’ve come up with this simple solution. Of course, you can take this to the next level and get really creative with it using a … that’s right, Preprocessor Macro!

- (NSString *)DateAndTime
{
    // Get the time
    NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    NSDate *date = [NSDate date];
    
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
    
    // Turn the date into Integers
    NSInteger year = [dateComponents year];
    NSInteger month = [dateComponents month];
    NSInteger day = [dateComponents day];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // This will produce a time that looks like "12:15:00 PM".
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    NSString *getTheDate = [NSString stringWithFormat:@"%d/%d/%d",month,day,year];
    
    NSString *getTheTime = [formatter stringFromDate:date];
    
    return [NSString stringWithFormat:@"%@ @ %@",getTheDate,getTheTime];
}

/*
 * Usage
 */

NSLog(@"Current Date and Time: %@", [self DateAndTime]);

/*
 * Console Output
 */

2012-08-18 03:29:21.406 WrightsCSApps[5759:1e203] Current Date and Time: 8/18/2012 @ 9:41 AM

Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

© Copyright 2011 Wright's Computer Services.   All rights reserved Suffusion theme by Sayontan Sinha