How do I get weekday and/or name of month from a NSDate variable?

后端 未结 8 1606
春和景丽
春和景丽 2020-12-08 03:09

Alright. The problem we\'re having is that we have NSStrings filled with dates in the format of yyyyMMdd and what we want to do is to get the current weekday and name of mon

相关标签:
8条回答
  • 2020-12-08 03:28
    - (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]]);
    
    }
    
    0 讨论(0)
  • 2020-12-08 03:33

    As apple says, creating (and let ARC dispose) a formatter is expensive, so:

    1) declare in your file:

    private var localDateFormatter : DateFormatter?
    
    ..
    extension Date {
    

    2) use lazy approach:

    if localDateFormatter == nil{
    
            localDateFormatter = DateFormatter()
    
            let locale = Locale(identifier: "en_US_POSIX")
    
    ....}
        let newTime = localDateFormatter!.date(from: self)
    

    if You have alla the stuff in one class, a static / let member would be nice. (we cannot use vars in extensions... :( globals seems bad but no way...)

    0 讨论(0)
提交回复
热议问题