2009-05-10 12 views
5

Estoy seguro de que me falta algo. Pero he buscado esto en Google durante días tratando de encontrar cómo mostrar un año de 4 dígitos cuando se muestra un NSDate con un estilo de NSDateFormatterShortStyle. Por favor, avíseme si tiene una solución. Aquí está el código que estoy usando ahora.iphone shortdate con 4 dígitos año

[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]; 

Respuesta

10

Si necesita cuatro años de dígitos, establezca la dateformat: utilizando el formato exacto que desea. La desventaja es que pierdes el formato de configuración regional automática.

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];    
} 

actualiza con Solución de error de Max Macleod

+0

gracias pero necesito que localiza – Dave

+0

para localizar, añada la línea dateFormatter.locale = [NSLocale autoupdatingCurrentLocale]; –

+0

en realidad, también necesitará un cheque en caso de que el formato específico de la localidad ya sea aaaa, p. if ([formatString rangeOfString: @ "aaaa"]. location == NSNotFound) { NSString * fourDigitYearFormat = [[dateFormatter dateFormat] stringByReplacingOccurrencesOfString: @ "yy" withString: @ "yyyy"]; [dateFormatter setDateFormat: fourDigitYearFormat]; } –

0

kCFDateFormatterShortStyle Especifica un estilo corto, por lo general sólo numérico, tales como “11/23/37” o “15:30”.

disponible en Mac OS X 10.3 y posteriores.

declarados en CFDateFormatter.h.

Source

NSDateFormatterShortStyle no aparece para darle 4 años dígitos.

+3

esto es una especie de mi punto no hay un formato que sea mes/día/año que proporcione años de 4 dígitos. si pongo un formato, pierdo localización. esta es mi frustración – Dave

+1

En realidad depende de la configuración regional: Dinamarca es una que le da años de 4 dígitos en formato corto. Es un gran caso de prueba porque no usa ':' en los tiempos. –

10

Sólo en caso de que alguien se tropieza aquí como lo hice porque yo necesitaba algo así con un año de 2 dígitos en un formato de fecha localizada y esto es una pregunta muy viejo, 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 utilizarlo en algún momento ...

+0

¡fantástico! Siempre he luchado con varias otras soluciones y esto llegó al núcleo. Gracias amigo. Mantenga el buen trabajo rodando. – Felipe

1

Ésta es una vieja thre anuncio, sino porque yo estaba tratando de hacer lo que Dave quería y no podía y porque ninguna de las respuestas dadas donde correcta, aquí está la solución (por si alguien quiere nunca es la misma cosa):

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]; 
Cuestiones relacionadas