Pregunta

Estoy seguro de que solo me falta algo. Pero he buscado en Google esto durante días tratando de encontrar cómo mostrar un año de 4 dígitos al mostrar un NSDate con un estilo de NSDateFormatterShortStyle. Avísame si tienes una solución. Aquí está el código que estoy usando ahora.

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];

    // add label for birth
    UILabel *birthday = [[UILabel alloc] initWithFrame:CGRectMake(125, 10, 100, 25)];
    birthday.textAlignment = UITextAlignmentRight;
    birthday.tag = kLabelTag;
    birthday.font = [UIFont boldSystemFontOfSize:14];
    birthday.textColor = [UIColor grayColor];
    birthday.text = [dateFormatter stringFromDate:p.Birth];
¿Fue útil?

Solución

Si necesita años de cuatro dígitos, configure el dateformat: utilizando el formato exacto que desee. La desventaja es que pierde el formato de configuración regional automático.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MM/dd/yyyy"];

...

birthday.text = [dateFormatter stringFromDate:p.Birth];

Si necesita localización, puede intentar modificar el formato de fecha del estilo corto.

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease ];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];

if ([[dateFormatter dateFormat] rangeOfString:@"yyyy"].location == NSNotFound) { 
    NSString *fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString:@"yy" withString:@"yyyy"]; 
    [dateFormatter setDateFormat:fourDigitYearFormat];             
}

Actualizado con Bugfix de Max Macleod

Otros consejos

En caso de que alguien tropiece aquí como yo, porque necesitaba algo así con un año de 2 dígitos en un formato de fecha localizado y esta es una pregunta muy antigua, aquí está mi solución:

NSLocale*           curLocale = [NSLocale currentLocale];
NSString*           dateFmt   = [NSDateFormatter dateFormatFromTemplate: @"ddMMyyyy"
                                                                options: 0
                                                                 locale: curLocale];
NSDateFormatter*    formatter = [[[NSDateFormatter alloc] init] autorelease];
                    [formatter setDateFormat:dateFmt];
NSString*           retText = [formatter stringFromDate:refDate];

return retText;

Tal vez alguien podría usarlo alguna vez ...

Este es un hilo viejo, pero porque estaba tratando de hacer lo que Dave quería y no podía y porque ninguna de las respuestas dadas era correcta, aquí está la solución (en caso de que alguien quiera lo mismo):

NSString *FormatString = [NSDateFormatter dateFormatFromTemplate:@"MM/dd/yyyy HH:mm" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:FormatString];
//Parse date here with the formater (like [formatter stringFromDate:date])
[formatter release];
  

kCFDateFormatterShortStyle   Especifica un estilo corto, típicamente numérico solamente, como & # 8220; 23/11/37 & # 8221; o & # 8220; 3: 30pm & # 8221 ;.

     

Disponible en Mac OS X v10.3 y posterior.

     

Declarado en CFDateFormatter.h.

Fuente

NSDateFormatterShortStyle no parece darle años de 4 dígitos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top