Swift:如何从nsdate获得工作日

时间:2016-05-19 10:57:43

标签: swift nsdate

我试图在应用程序中创建日历视图,我需要知道的一个项目是该月的第一天所依据的Int值。所以我可以正确地渲染其余部分。

我有以下代码

var CurrentDisplayDate      = NSDate()
var calendar                = NSCalendar.currentCalendar()
let DateComponents      = calendar.components([.Hour, .Month, .Year, .Weekday], fromDate: CurrentDisplayDate)
let StartWeekDay        = DateComponents.weekday

然而,它不断给我当天的工作日而不是本月的第一天。

由于

2 个答案:

答案 0 :(得分:0)

我认为你想要的是这样......

var calendar = NSCalendar.currentCalendar()
let today = NSDate()
let dateComponents = calendar.components([.Day, .Month, .Year], fromDate: today)
dateComponents.day = 1 // ** set the day of month to 1
// Get a real date back from the modified components
if let startDate = calendar.dateFromComponents(dateComponents) {
    // and extract the weekday from *that* date
    let startComponents = calendar.components([.Weekday, .Month, .Year], fromDate: startDate)
    let startWeekDay = startComponents.weekday
}

答案 1 :(得分:0)

试试这个我希望它会有所帮助!!!

let dateFormatter = NSDateFormatter()
let date = NSDate()
dateFormatter.dateFormat = "yyyy-MM-dd"
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date)

let month = components.month
let year = components.year

let startOfMonth = ("\(year)-\(month)-01")
print(startOfMonth)

你也可以用其他方式做到这一点

    let dateFormatter = NSDateFormatter()
    let date = NSDate()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([.Year, .Month], fromDate: date)
    let startOfMonth = calendar.dateFromComponents(components)!
    print(dateFormatter.stringFromDate(startOfMonth))