Localized date (month and day) and time with NSDate

I want to have a local date and time for where my application will run, based on the iPhone configuration. In particular, I need the date of the format mm / dd or dd / mm (or dd.mm, mm.dd, dd-mm, mm-dd, etc.) Depending on the locale, and the time is hh: mm. Is this possible with some combination of SDK methods?

Thanks!

+7
source share
2 answers

Well, I believe that the following code works for what I need:

NSString *dateComponents = @"yMMd"; NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:[NSLocale currentLocale]]; NSArray *tmpSubstrings = [dateFormat componentsSeparatedByString:@"y"]; NSString *tmpStr; NSRange r; if ([[tmpSubstrings objectAtIndex:0] length] == 0) { r.location = 1; r.length = [[tmpSubstrings objectAtIndex:1] length] - 1; tmpStr = [[tmpSubstrings objectAtIndex:1] substringWithRange:r]; } else { r.location = 0; r.length = [[tmpSubstrings objectAtIndex:0] length] - 1; tmpStr = [[tmpSubstrings objectAtIndex:0] substringWithRange:r]; } NSString *newStr = [[NSString alloc] initWithFormat:@"%@ H:mm", tmpStr]; NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:newStr]; NSString *formattedDateString = [formatter stringFromDate:[NSDate date]]; 
+6
source

I changed the code so that it simply deleted the date and time from the NSDate object without changes:

 NSDate* date = [NSDate date]; NSString* datePart = [NSDateFormatter localizedStringFromDate: date dateStyle: NSDateFormatterShortStyle timeStyle: NSDateFormatterNoStyle]; NSString* timePart = [NSDateFormatter localizedStringFromDate: date dateStyle: NSDateFormatterNoStyle timeStyle: NSDateFormatterShortStyle]; NSLog(@"Month Day: %@", datePart); NSLog(@"Hours Min: %@", timePart); 
+13
source

All Articles