programing tip

Foundation에서 요일을 어떻게 알 수 있습니까?

itbloger 2020. 8. 3. 08:42
반응형

Foundation에서 요일을 어떻게 알 수 있습니까?


요일을 문자열로 어떻게 알 수 있습니까?


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

현재 지역 설정에 따라 현재 요일을 로케일의 문자열로 출력합니다.

요일 숫자 만 얻으려면 NSCalendar 클래스를 사용해야합니다.

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:[NSDate date]];
int weekday = [comps weekday];

다음 세 줄만 사용하십시오.

CFAbsoluteTime at = CFAbsoluteTimeGetCurrent();
CFTimeZoneRef tz = CFTimeZoneCopySystem();
SInt32 WeekdayNumber = CFAbsoluteTimeGetDayOfWeek(at, tz);

여기서 많은 답변이 더 이상 사용되지 않습니다. 이것은 iOS 8.4부터 작동하며 요일을 문자열과 숫자로 제공합니다.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE"];
NSLog(@"The day of the week: %@", [dateFormatter stringFromDate:[NSDate date]]);

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *comps = [gregorian components:NSCalendarUnitWeekday fromDate:[NSDate date]];
int weekday = [comps weekday];
NSLog(@"The week day number: %d", weekday);

다음은 Swift 3에서 수행하고 현지화 된 요일 이름을 얻는 방법입니다.

let dayNumber = Calendar.current.component(.weekday, from: Date()) // 1 - 7
let dayName = DateFormatter().weekdaySymbols[dayNumber - 1]

-(void)getdate {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"MMM dd, yyyy HH:mm"];
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"HH:mm:ss"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init] ;
    [dateFormatter setDateFormat:@"EEEE"];

    NSDate *now = [[NSDate alloc] init];
    NSString *dateString = [format stringFromDate:now];
    NSString *theDate = [dateFormat stringFromDate:now];
    NSString *theTime = [timeFormat stringFromDate:now];

    NSString *week = [dateFormatter stringFromDate:now];
    NSLog(@"\n"
          "theDate: |%@| \n"
          "theTime: |%@| \n"
          "Now: |%@| \n"
          "Week: |%@| \n"
         , theDate, theTime,dateString,week); 
}

패턴 일치 알고리즘에 0 (일요일) 및 6 = 토요일을 사용하는 간단한 (그레고리 안) 요일 인덱스가 필요했습니다. 거기에서 인덱스를 사용하여 배열에서 요일 이름을 찾는 것이 간단합니다. 다음은 날짜 포맷터, NSCalendar 또는 날짜 구성 요소 조작이 필요없는 결과입니다.

+(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;
}

다음은 Swift 3에 대한 업데이트 된 코드입니다.

코드 :

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())

I think this topic is really useful, so I post some code Swift 2.1 compatible.

extension NSDate {

    static func getBeautyToday() -> String {
       let now = NSDate()
       let dateFormatter = NSDateFormatter()
       dateFormatter.dateFormat = "EEEE',' dd MMMM"
       return dateFormatter.stringFromDate(now)
    }

}

Anywhere you can call:

let today = NSDate.getBeautyToday()
print(today) ---> "Monday, 14 December"

Swift 3.0

As @delta2flat suggested, I update answer giving user the ability to specify custom format.

extension NSDate {

    static func getBeautyToday(format: String = "EEEE',' dd MMMM") -> String {
        let now = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: now)
    }

}

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.


This way it works in Swift:

    let calendar = NSCalendar.currentCalendar()
    let weekday = calendar.component(.CalendarUnitWeekday, fromDate: NSDate())

Then assign the weekdays to the resulting numbers.


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]  ;

Swift 2: Get day of week in one line. (based on neoscribe answer)

let dayOfWeek  = Int((myDate.timeIntervalSinceReferenceDate / (60.0*60.0*24.0)) % 7)
let isMonday   = (dayOfWeek == 0)
let isSunday   = (dayOfWeek == 6)

self.dateTimeFormatter = [[NSDateFormatter alloc] init];
self.dateTimeFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; // your timezone
self.dateTimeFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"]; // your locale
self.dateTimeFormatter.dateFormat = @"ccc MM-dd mm:ss";

there are three symbols we can use to format day of week:

  • E
  • e
  • c

The following two documents may help you.

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html

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

Demo:

you can test your pattern on this website:

http://nsdateformatter.com/

참고URL : https://stackoverflow.com/questions/4269093/how-do-i-get-the-day-of-the-week-with-foundation

반응형