2011-04-08 7 views
33

De acuerdo. El problema que tenemos es que tenemos NSStrings llenos con las fechas en el formato de aaaamMMdd y lo que queremos hacer es obtener el día de la semana actual y el nombre del mes. La función dagOmvandlare convierte la cadena de fechas en día de la semana y mes. La función se llama en viewDidload para nombrar todos nuestros botones-títulos de inglés a sueco meses.¿Cómo obtengo Weekday y/o el nombre del mes de una variable NSDate?

nuestra solución actual es el aspecto de esto:

-(NSString *)dagOmvandlare:(id) suprDatum{ 

    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
    dateFormatter.dateFormat = @"yyyyMMdd"; 

    NSDate *date = [dateFormatter dateFromString:suprDatum]; 


    NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil 
                 locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]; 

    if ([monthString isEqualToString:@"January"]) { 
     monthString = @"Januari"; 
    } 
    else 
     if ([monthString isEqualToString:@"February"]) { 
      monthString = @"Februari"; 
     } 
     else 
      if ([monthString isEqualToString:@"May"]) { 
       monthString = @"Maj"; 
      } 
      else 
       if ([monthString isEqualToString:@"June"]) { 
        monthString = @"Juni"; 
       } 
       else 
        if ([monthString isEqualToString:@"July"]) { 
         monthString = @"Juli"; 
        } 
        else 
         if ([monthString isEqualToString:@"August"]) { 
          monthString = @"Augusti"; 
         } 
         else 
          if ([monthString isEqualToString:@"October"]) { 
           monthString = @"Oktober"; 
          } 
          else 
           if ([monthString isEqualToString:@"March"]) { 
            monthString = @"Mars"; 
           } 

    return monthString; 

} 



- (void)viewDidLoad { 
    [super viewDidLoad]; 

    [button3 setTitle:(NSString *)[self dagOmvandlare:self.datum1] forState:UIControlStateNormal]; 
    [button2 setTitle:(NSString *)[self dagOmvandlare:self.datum2] forState:UIControlStateNormal]; 
    [bmanad1 setTitle:(NSString *)[self dagOmvandlare:self.datum3] forState:UIControlStateNormal]; 

} 

Y lo que hemos descubierto hasta ahora es que la

NSString * monthString = [date descriptionWithCalendarFormat:@"%B"timeZone:nil 
                 locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]]; 

no está permitido para ser utilizado por las directrices relativas a la no Manzanas api público. Entonces, la pregunta principal es, ¿qué otra forma hay para salir del día de la semana y el nombre del mes de nuestras cadenas de fechas que contienen fechas con el formato aaaaMMdd?

Respuesta

84

No hay necesidad de convertir manualmente a las palabras suecas. iPhone lo hará por ti. Prueba esto:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.dateFormat = @"yyyyMMdd"; 
NSDate *date = [dateFormatter dateFromString:@"20111010"]; 

// set swedish locale 
dateFormatter.locale=[[NSLocale alloc] initWithLocaleIdentifier:@"sv_SE"]; 

[email protected]"MMMM"; 
NSString *monthString = [[dateFormatter stringFromDate:date] capitalizedString]; 
NSLog(@"month: %@", monthString); 

[email protected]"EEEE"; 
NSString *dayString = [[dateFormatter stringFromDate:date] capitalizedString]; 
NSLog(@"day: %@", dayString); 

Salida:

month: Oktober 
day: Måndag 
+0

gracias. Funciona como un encanto, aunque la primera letra de todos los días/meses no es en mayúscula, pero ese es un problema muy leve para nosotros ATM :) – doge

+4

'[string capitalizedString]' ... corregido! –

+0

Gracias funcionó para mí ..... +1 para usted – Sabby

5

Esperanza esto ayuda

NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; 
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit; 
NSDate *date = [NSDate date]; 
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date]; 

NSInteger year = [dateComponents year]; 
NSInteger month = [dateComponents month]; 
NSInteger day = [dateComponents day]; 
NSInteger hour = [dateComponents hour]; 
NSInteger minute = [dateComponents minute]; 
NSInteger second = [dateComponents second]; 

[calendar release]; 

This podría ser útil

Otra cuestión de forma que podría ayudarle a How to find weekday from today's date using NSDate?

8
NSString *[email protected]"20110407"; 
NSDateFormatter *df=[[[NSDateFormatter alloc] init] autorelease]; 
[df setDateFormat:@"yyyyMMdd"]; 
NSDate *targetDate=[df dateFromString:strDate]; 
[df setDateFormat:@"EEEE MMMM dd, yyyy"]; 
NSString *s=[df stringFromDate:targetDate]; 

NSLog(@"Date: %@", s); 
+0

Esto también funciona! Gracias. – doge

1
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"EEEE"]; 
NSString *dayName = [dateFormatter stringFromDate:Date]; 

este nombre del día estará disponible en la configuración regional del usuario.

+0

Gracias descuidadoChoosy :) –

0
- (void) getMonthFromDate:(NSString *) stringDate 
{ 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd"]; 
    NSDate *date = [dateFormat dateFromString:stringDate]; 
    NSCalendar* calendar = [NSCalendar currentCalendar]; 
    NSDateComponents* components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:date]; // Get necessary date components 

    NSLog(@"%lu", [components day]); 
    NSLog(@"%lu %@",[components day],[[dateFormat monthSymbols] objectAtIndex:[components month]]); 

} 
8

simples Swift 3 extensiones:

// Weekday 
extension Date { 
    func dayOfWeek() -> String? { 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "EEEE" 
     return dateFormatter.string(from: self).capitalized 
     // or capitalized(with: locale) 
    } 
} 

print(Date().dayOfWeek()!) // Wednesday 

// Month Name 
extension Date { 
    func monthName() -> String? { 
     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "MMMM" 
     return dateFormatter.string(from: self).capitalized 
     // or capitalized(with: locale) 
    } 
} 

print(Date().monthName()!) // October 
+0

'return dateFormatter.string (from: self) .capitalized'? –

+0

¡Oh, broche de presión! Sí, arreglado. Gracias. – brandonscript

+0

Respuesta impresionante y gracias :) –

1

como dice Apple, crear (y seamos ARC disponer) un formateador es caro, así:

1) declarar en su archivo:

private var localDateFormatter : DateFormatter? 

.. 
extension Date { 

2) utilizar enfoque perezoso:

if localDateFormatter == nil{ 

     localDateFormatter = DateFormatter() 

     let locale = Locale(identifier: "en_US_POSIX") 

....} 
    let newTime = localDateFormatter!.date(from: self) 

si tiene todas las cosas en una clase, un miembro estático/let sería agradable. (no podemos usar vars en extensiones ... :(globals parece malo pero de ninguna manera ...)

Cuestiones relacionadas