Amine Arous
Amine Arous

Reputation: 635

Day Name From NSDate?

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

Upvotes: 39

Views: 26668

Answers (6)

Hemang
Hemang

Reputation: 27052

@Jilouc answer in Swift:

let formatter = DateFormatter.init()
formatter.dateFormat = "EEEE"
let date = Date.init() //or any date
let dayName = formatter.string(from: date)

Upvotes: 1

Peter Lapisu
Peter Lapisu

Reputation: 20975

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

Upvotes: 3

Amine Arous
Amine Arous

Reputation: 635

I found it, the answer was :

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

Thanks

Upvotes: 15

Jilouc
Jilouc

Reputation: 12714

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)

Upvotes: 118

petert
petert

Reputation: 6692

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

Upvotes: 0

Ken
Ken

Reputation: 13003

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.

Upvotes: 3

Related Questions