简体   繁体   中英

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

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)

I found it, the answer was :

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

Thanks

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

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.

@Jilouc answer in Swift:

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

有很多很好的日期和时间处理资源 - 这是我从github上学到的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM