views:

2303

answers:

3

I want current time in following format in a string.

dd-mm-yyyy HH:MM

How?

Thanks in advance.

Sagar

+9  A: 

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.
Carl Norum
Edited for iphone-ness.
Carl Norum
<pedantic>don't forget to release your formatter.</pedantic>
Frank Schmitt
Unless you want to keep it around; memory management may or may not enter into the problem.
Carl Norum
Date formatters are really slow to set up. If you are setting dates in a table cell or doing it a lot, as was mentioned above, you'll want to retain it, us it for everything, then release it in dealloc.
Steve Weller
+3  A: 

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);
Stephen Canon
Note that you can't do too much with a C string in Objective C. This might be more convenient when logging something to the console. You can just say `NSLog(@"%s", buffer)`.
Dustin Voss
Anything you can do with a C string in C, you can do in Objective-C. Which is to say, pretty much everything. One should feel free to use both C strings and NSStrings, and pick the appropriate one for the current use case. I personally would go with Carl's solution, but it's important to be aware that it's not the only way.
Stephen Canon
I would say the reason not to use strftime (despite it generating a C string that you then have to convert) is that you also lose out on the far greater flexibility of the NSDateFormatter date formatting options, including more variable length of numeric results and so on.
Kendall Helmstetter Gelner
Did I really get a down vote for demonstrating a (perfectly valid) alternative solution?
Stephen Canon
this should be the preferred way on iOS becayuse of this bug http://stackoverflow.com/questions/143075/nsdateformatter-am-i-doing-something-wrong-or-is-this-a-bug , however i am finding that time() or localtime_r() are not always accurate, am seeing very weird results.
valexa
A: 

1> If you are setting dates a lot,

2> you'll want to retain it, us it for everything,

3> then release it in dealloc

Can someone give a code example for #2?

Donna