Create a date in your format in IOS

By | December 31, 2014

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 *