tags:

views:

49

answers:

2

I am currently extacting yyyy mm dd hh mm and ss from NSDate like this:-

NSDate* dd   = [NSDate date];
NSString* date = [dd description];
NSString* y = [date substringToIndex:4];
NSString* m = [[date substringFromIndex:5] substringToIndex:2];
NSString* d = [[date substringFromIndex:8] substringToIndex:2];
NSString* h = [[date substringFromIndex:11] substringToIndex:2];
NSString* mi   = [[date substringFromIndex:14] substringToIndex:2];
NSString* s = [[date substringFromIndex:17] substringToIndex:2];
NSLog(@"%@, %@ %@ %@ %@ %@ %@,", date, y, m, d, h, mi, s);

But it seems dodgy to me e.g. what about locale? Is there a better way to do it, or is this locale-proof?

A: 

You can use NSDateFormatter, have a look at Apple documentation

rano
A: 

You should give the class NSDateFormatter a shot. This class is intended to do exactly that: creating locale-proof, localized, user-prefered date strings. You shouldn't use anything els for presenting dates to users.

Max Seelemann
Thank you.I had a look at NSDateFormatter and I think that answers my question i.e. NSDateFormatter will mess with the format to suit locale and so by implication, the above *won't* and what I want is the above i.e. it *won't* change with locale change (i.e. those values will stay in the same positions "despite" locale)?
Robin Pain
I am not too sure what exactly you're asking for. If it is to have a fixed date format, that does not adjust to anything, then it's the best to use `-descriptionWithCalendarFormat:timeZone:locale:`. You might figure the details from the documentation here: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/doc/uid/20000188--descriptionWithCalendarFormat_timeZone_locale_ Please continue to ask it you don't understand something...
Max Seelemann
Thanks again, this is exactly what I need e.g. I pass nil to it and it returns a string with the pieces in fixed places despite the locale.E.g. the code I am copying (from another SDK/language) has month(), day(), year() etc by parsing the above string I can re-create these functions despite different locales.
Robin Pain