NSDateformatter setDateFormat according to currentLocale

前端 未结 6 2147
孤城傲影
孤城傲影 2021-02-14 12:17

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 curr

相关标签:
6条回答
  • 2021-02-14 12:30

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

    0 讨论(0)
  • 2021-02-14 12:34

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

    0 讨论(0)
  • 2021-02-14 12:41

    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];
    
    0 讨论(0)
  • 2021-02-14 12:41
    -(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.

    0 讨论(0)
  • 2021-02-14 12:44

    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)
    
    0 讨论(0)
  • 2021-02-14 12:53

    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

    0 讨论(0)
提交回复
热议问题