Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localized date (month and day) and time with NSDate

I want to be able to get the local date and time for wherever my app is run, based on the iPhone configuration. Specifically I need the date to be of format mm/dd or dd/mm (or dd.mm, mm.dd, dd-mm, mm-dd, etc) depending on the locale, and time is hh:mm. Is this possible with some combination of SDK methods?

Thanks!

like image 872
DNewell Avatar asked Mar 03 '11 23:03

DNewell


2 Answers

I have modified the code so that it just takes the date and time out of the NSDate object with no 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);
like image 112
Daniel T. Avatar answered Nov 15 '22 21:11

Daniel T.


Well, I believe 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]];
like image 45
DNewell Avatar answered Nov 15 '22 21:11

DNewell