Swiftでカレンダーを簡単に作ることができるライブラリFSCalenderで日本時間を取得する方法です。
変換用のswiftファイルを作成する。
import Foundation
import UIKit
class DateUtils {
class func dateFromString(string: String, format: String) -> Date {
let formatter: DateFormatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = format
return formatter.date(from: string)!
}
class func stringFromDate(date: Date, format: String) -> String {
let formatter: DateFormatter = DateFormatter()
formatter.calendar = Calendar(identifier: .gregorian)
formatter.dateFormat = format
return formatter.string(from: date)
}
}
ViewController.swiftを次のように記載します。
import UIKit
import FSCalendar;
class ViewController: UIViewController, FSCalendarDataSource, FSCalendarDelegate {
@IBOutlet weak var calendar: FSCalendar!
override func viewDidLoad() {
super.viewDidLoad()
//ついでに日本語化
self.calendar.appearance.headerDateFormat = "YYYY年MM月"
self.calendar.calendarWeekdayView.weekdayLabels[0].text = "日"
self.calendar.calendarWeekdayView.weekdayLabels[1].text = "月"
self.calendar.calendarWeekdayView.weekdayLabels[2].text = "火"
self.calendar.calendarWeekdayView.weekdayLabels[3].text = "水"
self.calendar.calendarWeekdayView.weekdayLabels[4].text = "木"
self.calendar.calendarWeekdayView.weekdayLabels[5].text = "金"
self.calendar.calendarWeekdayView.weekdayLabels[6].text = "土"
calendar.dataSource = self
calendar.delegate = self
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition)
{
print(DateUtils.stringFromDate(date: date, format: "yyyy/MM/dd HH:mm:ss"))
}
}