Created
January 20, 2017 09:57
-
-
Save vc7/0139f9e9c69eccde505470bd10de4650 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import UIKit | |
| func printCalendar(year: Int, month: Int) { | |
| if month < 1 || month > 12 { | |
| return | |
| } | |
| let calendar = Calendar(identifier: .gregorian) | |
| var givenComponents = DateComponents() | |
| givenComponents.year = year | |
| givenComponents.month = month | |
| givenComponents.day = 1 | |
| let date = calendar.date(from: givenComponents) | |
| /// 本月天數 | |
| let days = calendar.range(of: .day, in: .month, for: date!) | |
| let components = calendar.dateComponents([.weekday], from: date!) | |
| /// 取得第一天是星期幾 | |
| let firstWeekday = components.weekday! | |
| // MARK: - Composing Weeks Array | |
| var currentDay = 1 | |
| var currentWeek = 1 | |
| var currentWeekday = firstWeekday | |
| var weeksArray: [[Int]] = [] | |
| while currentDay < days!.upperBound { | |
| if currentWeekday > 7 { | |
| weeksArray.append([]) | |
| currentWeekday = 1 | |
| currentWeek += 1 | |
| } | |
| if currentDay == 1 { | |
| weeksArray.append([]) | |
| } | |
| weeksArray[currentWeek-1].append(currentDay) | |
| currentWeekday += 1 | |
| currentDay += 1 | |
| } | |
| // MARK: - Print Result | |
| // Print symbols | |
| let formatter = DateFormatter() | |
| formatter.locale = Locale(identifier: "zh_TW") | |
| let symbols = formatter.veryShortWeekdaySymbols.joined(separator: "\t") | |
| print(symbols) | |
| // Print days | |
| for (index, daysArray) in weeksArray.enumerated() { | |
| var weekString = "" | |
| if index == 0 { | |
| for _ in (1..<firstWeekday) { | |
| weekString.append("\t") | |
| } | |
| } | |
| for day in daysArray { | |
| weekString.append("\(day)\t") | |
| } | |
| print(weekString) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment