NSDateformatter setDateFormat according to current

2020-06-12 03:58发布

I'm going mad with, probably, a stupid problem.

I have 3 strings: year, month and day. I need to have a date in the right format based on currentLocale, so i.e. if currentLocale localeIdentifier is en_US my dateFormat should be: MMM/dd/yyyy

if it's fr_FR the dateFormat should be dd/MMM/yyyy

I don't think the only way to do this is to get currentLocale localeIdentifier and start with a bunch of if then.

Thanks in advance.

Max

6条回答
时光不老,我们不散
2楼-- · 2020-06-12 04:04

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).

查看更多
够拽才男人
3楼-- · 2020-06-12 04:05
-(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.

查看更多
别忘想泡老子
4楼-- · 2020-06-12 04:09

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

查看更多
Ridiculous、
5楼-- · 2020-06-12 04:14

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)
查看更多
放荡不羁爱自由
6楼-- · 2020-06-12 04:17

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

查看更多
放我归山
7楼-- · 2020-06-12 04:20

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];
查看更多
登录 后发表回答