objective iphone nsdate nsdateformatter

iphone - objective - NSDate en estilo completo pero sin año



ios dateformatter (5)

Swift 3

let template = "EEEEdMMM" let format = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: NSLocale.current) let formatter = DateFormatter() formatter.dateFormat = format let now = Date() let whatYouWant = formatter.string(from: now) // ex: Sunday, Mar 5

Juega con la template para satisfacer tus necesidades.

Doc y ejemplos here para ayudarle a determinar el patrón que desea.

Estoy trabajando con Objective C para iPhone y tengo un NSDate que quiero mostrar en estilo completo pero sin el año. Ahora mismo estoy usando el código de abajo, pero también muestra el año, y no quiero eso. Como quiero mostrar la fecha en el formato de la región correcta, no puedo eliminar el año al final, ya que en algunos países el año no será el final sino el medio o el principio.

NSDate *testdate = [NSDate date]; NSDateFormatter *dateFormattertest = [[NSDateFormatter alloc] init]; [dateFormattertest setDateStyle:NSDateFormatterFullStyle]; [dateFormattertest setTimeStyle:NSDateFormatterNoStyle]; NSString *formattedDateString = [dateFormattertest stringFromDate:testdate]; NSLog(formattedDateString); In US this give me: Thursday, January 14, 2010 In Sweden this give me: torsdag, 2010 januari 14

¿Cuál es la solución para esto? Y otra pregunta, ¿dónde puedo encontrar información sobre cómo usar setDateFormat de NSDateFormatter? No puedo encontrar información sobre qué significan las diferentes letras en la API.


Aquí hay una opción rápida para mostrar solo la fecha del mes en una etiqueta:

let todaysDate: NSDate = NSDate() let formatter = NSDateFormatter() formatter.dateFormat = "MMMM dd" self.todayLabel.text = formatter.stringFromDate(todaysDate)


Sé que esta es una pregunta bastante antigua, pero esta es la única que encontré en SO que hablaba del mismo problema que estaba teniendo.

El método clave para usar aquí es: dateFormatFromTemplate

En lugar de configurar el estilo, desea establecer el formato como tal:

NSDate *testdate = [NSDate date]; NSLocale *currentLocale = [NSLocale currentLocale]; // Set the date components you want NSString *dateComponents = @"EEEEMMMMd"; // The components will be reordered according to the locale NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:currentLocale]; NSLog(@"Date format for %@: %@", [currentLocale displayNameForKey:NSLocaleIdentifier value:[currentLocale localeIdentifier]], dateFormat); NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:dateFormat]; NSString *formattedDateString = [dateFormatter stringFromDate:testdate]; NSLog(formattedDateString);

Gracias especiales a: http://oleb.net/blog/2011/11/working-with-date-and-time-in-cocoa-part-2/


Tomó la gran respuesta de @Joss a una extensión de Swift:

extension NSDate { func formattedFromCompenents(styleAttitude: NSDateFormatterStyle, year: Bool = true, month: Bool = true, day: Bool = true, hour: Bool = true, minute: Bool = true, second: Bool = true) -> String { let long = styleAttitude == .LongStyle || styleAttitude == .FullStyle var comps = "" if year { comps += long ? "yyyy" : "yy" } if month { comps += long ? "MMMM" : "MMM" } if day { comps += long ? "dd" : "d" } if hour { comps += long ? "HH" : "H" } if minute { comps += long ? "mm" : "m" } if second { comps += long ? "ss" : "s" } let format = NSDateFormatter.dateFormatFromTemplate(comps, options: 0, locale: NSLocale.currentLocale()) let formatter = NSDateFormatter() formatter.dateFormat = format return formatter.string(from: self) } }


Swift 4

extension Date { public func formattedFromComponents(styleAttitude: DateFormatter.Style, year: Bool = false, month: Bool = false, day: Bool = false, hour: Bool = false, minute: Bool = false, second: Bool = false, locale: Locale = Locale.current) -> String { let long = styleAttitude == .long || styleAttitude == .full let short = styleAttitude == .short var comps = "" if year { comps += long ? "yyyy" : "yy" } if month { comps += long ? "MMMM" : (short ? "MM" : "MMM") } if day { comps += long ? "dd" : "d" } if hour { comps += long ? "HH" : "H" } if minute { comps += long ? "mm" : "m" } if second { comps += long ? "ss" : "s" } let format = DateFormatter.dateFormat(fromTemplate: comps, options: 0, locale: locale) let formatter = DateFormatter() formatter.dateFormat = format return formatter.string(from: self) } }