Getting the current time in a string in a custom format in lens c

I need the current time in the following format per line.

dd-mm-yyyy HH: MM

How?

+47
datetime objective-c iphone nstimer
Nov 06 '09 at 1:50
source share
4 answers

You want a date format . Here is an example:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"dd-MM-yyyy HH:mm"]; NSDate *currentDate = [NSDate date]; NSString *dateString = [formatter stringFromDate:currentDate]; 
+128
Nov 06 '09 at 1:53
source share

Use NSDateFormatter , as Carl said, or just use the good old strftime , which is also Objective-C great:

 #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); 
+15
Nov 06 '09 at 3:29
source share

Here is a simple solution:

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

Change dateStyle and timeStyle according to formatting requirements.

+7
Feb 25 '14 at 5:42
source share

Perhaps 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 the built-in obj-c NSDateFormatter named date , then apply it using [[NSDateFormatter alloc] init]; . After that, we tell the code process that we want our date to have HOUR / MINUTE / SECOND. Finally, we must make our date a string to work with a warning or set the label value, for this we must create a string with the NSString method, then we will use this: [date stringFromDate: [NSDate date]]

Have some fun with it.

+3
Jun 04
source share



All Articles