swift 在Swift中使用日期,日历。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 在Swift中使用日期,日历。相关的知识,希望对你有一定的参考价值。

// Playground - noun: a place where people can play

import UIKit

// Setup the calendar object
let calendar = NSCalendar.currentCalendar()

// Set up date object
let date = NSDate()

// Create an NSDate for the first and last day of the month
//let components = calendar.components(NSCalendarUnit.CalendarUnitYear |
//                                     NSCalendarUnit.CalendarUnitMonth |
//                                     NSCalendarUnit.WeekdayCalendarUnit |
//                                     NSCalendarUnit.WeekCalendarUnit |
//                                     NSCalendarUnit.CalendarUnitDay,
//                                     fromDate: date)

// Create an NSDate for the first and last day of the month
let components = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: date)


components.month

// Getting the First and Last date of the month
components.day = 1
let firstDateOfMonth: NSDate = calendar.dateFromComponents(components)!

components.month  += 1
components.day     = 0
let lastDateOfMonth: NSDate = calendar.dateFromComponents(components)!

var unitFlags = NSCalendarUnit.WeekOfMonthCalendarUnit |
                NSCalendarUnit.WeekdayCalendarUnit     |
                NSCalendarUnit.CalendarUnitDay

let firstDateComponents = calendar.components(unitFlags, fromDate: firstDateOfMonth)
let lastDateComponents  = calendar.components(unitFlags, fromDate: lastDateOfMonth)

// Sun = 1, Sat = 7
let firstWeek = firstDateComponents.weekOfMonth
let lastWeek  = lastDateComponents.weekOfMonth

let numOfDatesToPrepend = firstDateComponents.weekday - 1
let numOfDatesToAppend  = 7 - lastDateComponents.weekday + (6 - lastDateComponents.weekOfMonth) * 7

let startDate: NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -numOfDatesToPrepend, toDate: firstDateOfMonth, options: nil)!
let endDate:   NSDate = calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: numOfDatesToAppend, toDate: lastDateOfMonth, options: nil)!

Array(map(0..<42) {
    calendar.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: $0, toDate: startDate, options: nil)!
})

"\(components.year)"


var dateString = "2014-10-3" // change to your date format
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd"

var someDate = dateFormatter.dateFromString(dateString)
println(someDate)

以上是关于swift 在Swift中使用日期,日历。的主要内容,如果未能解决你的问题,请参考以下文章

Swift FSCalendar 在表格视图的日历显示事件中选择日期

swift 从swift中的日期获取日历信息。

swift中的日期格式错误

Swift 日历类库 JTAppleCalendar

swift 3或objective c中的水平日历视图

@distinctUnionOfObjects 可以在 Swift 中使用吗?