How do I format the current date for the user's locale?

后端 未结 4 781
难免孤独
难免孤独 2021-02-05 09:00

I have this code where I\'m trying to get the current date and format it in the current locale.

NSDate *now = [NSDate date];  //  gets current date
NSString *sNo         


        
4条回答
  •  萌比男神i
    2021-02-05 09:22

    In addition to jiayow answer you can specify your custom 'template' to get localized version:

    + (NSString *)formattedDate:(NSDate *)date usingTemplate:(NSString *)template {
        NSDateFormatter* formatter = [NSDateFormatter new];
    
        formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:template options:0 locale:formatter.locale];
    
        return [formatter stringFromDate:date];
    }
    

    Example usage for US/DE locale:

    NSLocale *enLocale = [NSLocale localeWithLocaleIdentifier:@"en_US"];
    NSLocale *deLocale = [NSLocale localeWithLocaleIdentifier:@"de"];
    
    // en_US:   MMM dd, yyyy
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddMMMyyyy" options:0 locale:enLocale];
    // de:      dd. MMM yyyy
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddMMMyyyy" options:0 locale:deLocale];
    
    // en_US:   MM/dd/yyyy
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddyyyyMM" options:0 locale:enLocale];
    // de:      dd.MM.yyyy
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"ddyyyyMM" options:0 locale:deLocale];
    
    // en_US    MM/dd
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMdd" options:0 locale:enLocale];
    // de:      dd.MM.
    formatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"MMdd" options:0 locale:deLocale];
    

提交回复
热议问题