【问题标题】:How do I get the day of the week with Foundation?我如何通过 Foundation 获取星期几?
【发布时间】:2011-05-15 05:19:42
【问题描述】:

如何以字符串形式获取星期几?

【问题讨论】:

    标签: ios objective-c cocoa-touch nsdate


    【解决方案1】:
    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];
    

    【讨论】:

    • 要获取所有工作日的名称,您可以使用[dateFormatter weekdaySymbols](和类似的),它返回一个 NSArray 的 NSStrings 从索引 0 的星期日开始。
    • 好的,我如何从星期一而不是星期日开始获取星期几?
    • @VovaStajilov 这个问题:stackoverflow.com/questions/1106943/… 可能会有所帮助。基本上你需要将日历的第一个 weekDay 设置为星期一 ([calendar setFirstWeekday:2])
    • 第一个 NSLog 返回 475221968,这是一个不切实际的巨大数字。 . .
    • 好的,@Vladimir,我设置了[gregorian setFirstWeekday:2];星期一 01/06/2015 我收到了 2 个 ([components weekday])。为什么? - 我找到答案here
    【解决方案2】:

    只需使用这三行:

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

    【讨论】:

    • 我喜欢它,但对于一些新开发者来说,这几乎算作混淆(这可能是一个邪恶的奖励);)
    • CFAbsoluteTimeGetDayOfWeek 在 iOS 8 中已弃用。是否有使用 CFCalendar 的替代方法?
    【解决方案3】:

    这里的许多答案已被弃用。这适用于 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);
    

    【讨论】:

    • 附注 - 因为NSCalendarweekday 组件是NSInteger,如果需要,您需要将[comps weekday] 转换为int,否则它会显示一个警告。
    【解决方案4】:

    这是在 Swift 3 中的操作方法,并获得本地化的日期名称……

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

    【讨论】:

    • 在 Swift 3 中,应该使用 Calendar 而不是 NSCalendar。
    【解决方案5】:
    -(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); 
    }
    

    【讨论】:

      【解决方案6】:

      我需要一个简单的(公历)星期索引,其中 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;
      }
      

      【讨论】:

        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

          我觉得这个话题真的很有用,所以我发布了一些兼容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)
              }
          
          }
          

          【讨论】:

          • 这是本地化的吗?如果您的目标国家想要使用“12 月 14 日,星期一”或“12 月 14 日星期一”怎么办?应该在里面处理
          • 嗨@delta2flat。是的,格式已本地化。顺便说一句,我已经更新了答案:现在用户可以指定自定义格式
          • 太棒了 - 我发现 Objective-C / Cocoa Touch 非常强大,可以根据语言环境流畅地本地化字符串。
          • 你的 Swift 三个扩展名应该是 Date 而不是 NSDate。
          【解决方案9】:

          弗拉基米尔的回答对我来说效果很好,但我认为我会发布日期格式字符串的 Unicode 链接。

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

          此链接适用于 iOS 6。其他版本的 iOS 有不同的标准,可以在 X-Code 文档中找到。

          【讨论】:

            【解决方案10】:

            这样它在 Swift 中工作:

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

            然后将工作日分配给结果数字。

            【讨论】:

            • NSDate() 返回 GMT+0 的当前日期,对吗?你这里只是用 NSDate 举例,还是日历组件会自动检测当前的语言环境和时移?
            【解决方案11】:

            我在获得一周中的某一天时遇到了很奇怪的问题。仅设置 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]  ;
            

            【讨论】:

              【解决方案12】:

              Swift 2:在一行中获取星期几。 (based on neoscribe answer)

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

              【讨论】:

                【解决方案13】:
                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

                演示:

                你可以在这个网站上测试你的模式:

                http://nsdateformatter.com/

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2015-09-19
                  • 2016-10-22
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2017-02-18
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多