39

I would like to show the name of day in my iPhone application and i don't found the solution. Thanks for help

Amine Arous
  • 635
  • 1
  • 6
  • 13

6 Answers6

118
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSString *dayName = [dateFormatter stringFromDate:yourDate];
[dateFormatter release];

You get dayName in the locale of the user.

(check Unicode standards for date formats samples)

Jilouc
  • 12,684
  • 4
  • 46
  • 43
  • FYI different versions of iOS/macOS use different versions of the Unicode standard; I found an older table of them at https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html – rakslice Nov 06 '16 at 07:24
  • I am getting an abreviation with this: "Thu" – htafoya Mar 17 '17 at 04:50
15

I found it, the answer was :

NSDate *now = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@",[dateFormatter stringFromDate:now]);

Thanks

Amine Arous
  • 635
  • 1
  • 6
  • 13
3

NSDate category

+ (NSString *)dayNameWith0Monday:(NSInteger)index {

    static NSDateFormatter * DateFormatter = nil;
    if (DateFormatter == nil) {
        DateFormatter = [[NSDateFormatter alloc] init];
        [DateFormatter setDateFormat:@"EEEE"];
        [DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    }

    NSDate * day = [NSDate dateWithTimeIntervalSince1970:((4 * 24 * 60 * 60) + (24 * 60 * 60 * index))];
    return [DateFormatter stringFromDate:day];
}

0 will always be Monday! in case you need such behaviour

Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179
3

Look at -[NSCalendar components:fromDate:].

A date by itself doesn't have a day, because it may have different days in different calendars (Gregorian, Chinese, etc.).

EDIT: actually, sorry. That's what you would do to get the day and work with it programmatically. If you only want to display the day, look at NSDateFormatter.

Ken
  • 12,933
  • 4
  • 29
  • 32
1

@Jilouc answer in Swift:

let formatter = DateFormatter.init()
formatter.dateFormat = "EEEE"
let date = Date.init() //or any date
let dayName = formatter.string(from: date)
Hemang
  • 26,840
  • 19
  • 119
  • 186
0

There a many great resources for date and time processing - this is one I've learnt from over on github.

petert
  • 6,672
  • 3
  • 38
  • 46