Sunday, April 22, 2012

Getting Current Time in string in Custom format in objective c


I want current time in following format in a string.



dd-mm-yyyy HH:MM



How?



Thanks in advance.



Sagar


Source: Tips4all

2 comments:

  1. You want a date formatter. Here's an example:

    NSDateFormatter *formatter;
    NSString *dateString;

    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy HH:mm"];

    dateString = [formatter stringFromDate:[NSDate date]];

    [formatter release]; // maybe; you might want to keep the formatter
    // if you're doing this a lot.

    ReplyDelete
  2. Either use NSDateFormatter as Carl said, or just use good old strftime, which is also perfectly valid Objective-C:

    #import <time.h>
    time_t currentTime = time(NULL);
    struct tm timeStruct;
    localtime_r(&currentTime, &timeStruct);
    char buffer[20];
    strftime(buffer, 20, "%d-%m-%Y %H:%M", &timeStruct);

    ReplyDelete