NSDateformatter setDateFormat according to currentLocale

回眸只為那壹抹淺笑 提交于 2019-12-03 11:57:45

Look at NSDateComponents to create an NSDate, then use NSDateFormatter to format it. NSDateFormatter uses the current locale to format dates, based on the format style (e.g.
NSDateFormatterMediumStyle).

edc1591

If I understand your question, you want to set your NSDateFormatter to the locale of the user's device. For that you can just do something like this:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSDate *date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];

In Swift 3:

let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
formatter.locale = Locale.current
let date = Date()
let dateString = formatter.string(from: date)
print(dateString)
-(NSString *) stringFromDate:(NSDate *) date{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setLocale:[NSLocale currentLocale]];

    NSString *dateString = [dateFormatter stringFromDate:date];

    [dateFormatter release];

    return dateString;
}

-(NSDate *) dateFromString:(NSString *) dateInString{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];

    [dateFormatter setLocale:[NSLocale currentLocale]];

    NSDate *dateFromString = [dateFormatter dateFromString:dateInString];

    [dateFormatter release];

    return dateFromString;
}

I hope this helps.

check out this link to get understand of how NSDateFormatter based on http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/

Joss

In case you want to have more flexibility about the format than the formats usable with setDateStyle, have a look at my answer to a similar question: https://stackoverflow.com/a/20219610/1896336

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!