开发者

Day Name From NSDate?

I would like to show the name of day in my iPh开发者_JAVA百科one 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


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.


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


@Jilouc answer in Swift:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜