How do I get the day of the week with Foundation?

2019-01-02 17:37发布

How do I get the day of the week as a string?

13条回答
伤终究还是伤i
2楼-- · 2019-01-02 17:55

I needed a simple (Gregorian) day of the week index, where 0=Sunday and 6=Saturday to be used in pattern match algorithms. From there it is a simple matter of looking up the day name from an array using the index. Here is what I came up with that doesn't require date formatters, or NSCalendar or date component manipulation:

+(long)dayOfWeek:(NSDate *)anyDate {
    //calculate number of days since reference date jan 1, 01
    NSTimeInterval utcoffset = [[NSTimeZone localTimeZone] secondsFromGMT];
    NSTimeInterval interval = ([anyDate timeIntervalSinceReferenceDate]+utcoffset)/(60.0*60.0*24.0);
    //mod 7 the number of days to identify day index
    long dayix=((long)interval+8) % 7;
    return dayix;
}
查看更多
刘海飞了
3楼-- · 2019-01-02 17:56

Here is the updated code for Swift 3

Code :

let calendar = Calendar(identifier: .gregorian)

let weekdayAsInteger = calendar.component(.weekday, from: Date())

To Print the name of the event as String:

 let dateFromat = DateFormatter()

datFormat.dateFormat = "EEEE"

let name = datFormat.string(from: Date())
查看更多
春风洒进眼中
4楼-- · 2019-01-02 17:56

Vladimir's answer worked well for me, but I thought that I would post the Unicode link for the date format strings.

http://www.unicode.org/reports/tr35/tr35-25.html#Date_Format_Patterns

This link is for iOS 6. The other versions of iOS have different standards which can be found in the X-Code documentation.

查看更多
低头抚发
5楼-- · 2019-01-02 17:58

I had quite strange issue with getting a day of week. Only setting firstWeekday wasn't enough. It was also necesarry to set the time zone. My working solution was:

 NSCalendar* cal = [NSCalendar currentCalendar];
 [cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
 [cal setFirstWeekday:1]; //Sunday
 NSDateComponents* comp = [cal components:( NSWeekOfMonthCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit | NSWeekCalendarUnit)  fromDate:date];
 return [comp weekday]  ;
查看更多
荒废的爱情
6楼-- · 2019-01-02 18:00
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];  
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);

outputs current day of week as a string in locale dependent on current regional settings.

To get just a week day number you must use NSCalendar class:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];
查看更多
笑指拈花
7楼-- · 2019-01-02 18:01

Here's how you do it in Swift 3, and get a localised day name…

let dayNumber = Calendar.current.component(.weekday, from: Date()) // 1 - 7
let dayName = DateFormatter().weekdaySymbols[dayNumber - 1]
查看更多
登录 后发表回答