Как я могу получить день недели с Cocoa Touch?


Как получить день недели в виде строки в Objective-C?

13 106

13 ответов:

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

выводит текущий день недели в виде строки в locale в зависимости от текущих региональных настроек.

чтобы получить только номер дня недели, вы должны использовать класс 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);
-(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); 
}

вот как вы это делаете в Swift 3, и получите локализованное имя дня...

let dayNumber = Calendar.current.component(.weekday, from: Date()) // 1 - 7
let dayName = DateFormatter().weekdaySymbols[dayNumber - 1]
+(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())

чтобы вывести имя события в виде строки:

 let dateFromat = DateFormatter()

datFormat.dateFormat = "EEEE"

let name = datFormat.string(from: Date())

Я думаю, что эта тема действительно полезна, поэтому я публикую некоторый код Swift 2.1 совместимость.

extension NSDate {

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

}

в любом месте вы можете позвонить:

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

Swift 3.0

как предложил @delta2flat, я обновляю ответ, давая пользователю возможность указать пользовательский формат.

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

}

ответ Владимира работал хорошо для меня, но я думал, что я опубликую ссылку Unicode для строк формата даты.

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

эта ссылка предназначена для iOS 6. Другие версии iOS имеют различные стандарты, которые можно найти в документации X-Code.

таким образом, он работает в Swift:

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

затем назначьте выходные дни для результирующих чисел.

У меня довольно странная проблема с днем недели. Только установка firstWeekday не было достаточно. Также необходимо было установить часовой пояс. Мое рабочее решение было:

 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: Получить день недели в одной строке. (на основе ответа neoscribe)

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

есть три символа, которые мы можем использовать для форматирования дня недели:

  • E
  • e
  • c

следующие два документа могут помочь вы.

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:

вы можете проверить свой шаблон на этот сайт:

http://nsdateformatter.com/