Getting Current Time in string in Custom format in objective c

IphoneObjective CDatetimeNstimer

Iphone Problem Overview


I want current time in following format in a string.

dd-mm-yyyy HH:MM

How?

Iphone Solutions


Solution 1 - Iphone

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

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

NSDate *currentDate = [NSDate date];
NSString *dateString = [formatter stringFromDate:currentDate];

Solution 2 - Iphone

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);

Solution 3 - Iphone

Here is a simple solution:

- (NSString *)stringWithDate:(NSDate *)date
{
  return [NSDateFormatter localizedStringFromDate:date
                                        dateStyle:NSDateFormatterMediumStyle
                                        timeStyle:NSDateFormatterNoStyle];
}

Change the dateStyle and timeStyle to match your formatting requirement.

Solution 4 - Iphone

Maybe this will be more readable :

    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    [date setDateFormat:@"HH:mm"];
    NSString *dateString = [date stringFromDate:[NSDate date]];
    [self.time setText:dateString];

First of all we create an NSDateFormatter built-in in obj-c with the name date, then we apply it by [[NSDateFormatter alloc] init]; . After that we say to the code procesor that we want our date to have HOUR/MINUTE/SECOND. Finally we should make our date to be an string to work with alert or set value of a label , to do this we should create an string with NSString method then we use this : [date stringFromDate:[NSDate date]]

Have Fun with It .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSagar KothariView Question on Stackoverflow
Solution 1 - IphoneCarl NorumView Answer on Stackoverflow
Solution 2 - IphoneStephen CanonView Answer on Stackoverflow
Solution 3 - IphoneZorayrView Answer on Stackoverflow
Solution 4 - IphoneAmirHosseinView Answer on Stackoverflow