Below functions takes the current date and time and formats it to give a date-time string.
You can customise it in the way you want.

The string that the below function generates will be like this – 23-Dec-2014 4:23 PM

//Get the current date...
+(NSDate *) getCurrentDate
    NSDate *now = [NSDate date];
    return now;

//Get the date and time in a formatted way...
+(NSString *) getFormattedDateAndTime
    NSDate *now = [Global getCurrentDate];
    int hour;
    NSString *am_pm;
    //Get calendar Instance
    NSCalendar *cal=[NSCalendar currentCalendar];

    //optionally set the Locale
    //NSTimeZone *tz=[NSTimeZone timeZoneWithName:@"America/Chicago"];
    //[cal setTimeZone:tz];

    NSDateComponents *comp=[cal components:NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MMM-yyyy"];
    NSString *stringFromDate = [formatter stringFromDate:now];

    hour = (int)[comp hour];
    am_pm = (hour >= 12) ? @"PM" : @"AM";
    if(hour >= 12){
        hour = hour - 12;
    // 23-Dec-2014 4:23 PM
    NSString *dateTimeStr = [NSString stringWithFormat:@"%@ %d %d %@", 
                            stringFromDate, (int)hour, (int)[comp minute], am_pm];
    return dateTimeStr;

Use “MMMM” for “December” and “MMM” for “Dec” in month.


Leave a Reply

Your email address will not be published. Required fields are marked *




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.