【问题标题】:Swift 2.0+ finding the day of the week a month startsSwift 2.0+ 查找一个月的星期几开始
【发布时间】:2015-11-12 06:57:35
【问题描述】:

我正在使用 Swift 2.0+ 并且需要它与 iOS 8.0+ 兼容。我想知道一个月的星期几开始。例如,11 月 15 日将返回星期日,12 月 15 日将返回星期二,1 月 16 日将返回星期五。我认为最好的方法是获取当前星期几和月份中的某一天,然后倒数直到达到 1 并得到那一天。目前我有

// Returns the day of the week as an integer 1 being Sunday and 7 being Saturday
func dayOfWeek() -> Int {
        let components = calender.component(NSCalendarUnit.Weekday, fromDate: t)
        return components
    }

计算一周中的当前日期,之后我遇到了障碍。

【问题讨论】:

    标签: ios8 nsdate swift2 foundation nscalendar


    【解决方案1】:

    我找到了答案

    // This function should return the value I need 0 being Sunday and 6 being Saturday
        func dayMonthStarted() -> Int {
            // 0 -> Sunday 6 -> Saturday
            var component = calender.component(NSCalendarUnit.Day, fromDate: date)
            var day = dayOfWeek()
            while component > 1 {
                component--
                if day == 0 {
                    day = 6
                } else {
                    day--
                }
            }
    
            return day - 1
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 2013-02-15
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      相关资源
      最近更新 更多