JTAppleCalendar How to set current date and current month - jtapplecalendar

Hi I am newbie to JTAppleCalendar. I need help.
I have installed it thru cocoapods and used some of the code as below.
I need help on how to use the basic functions such as:
Set the calendar for the current month
JTC.scrollToDate(Date())
show the current date on the calendar.
Do I need to specify or configure how many years this calendar support like 100 or 200 years?
Is this way correct to get a reference for the JTAppleCalendar
#IBOutlet weak var JTC: JTAppleCalendarView!
Please help to correct the code.
import UIKit
import JTAppleCalendar
class ViewController: UIViewController {
let formatter = DateFormatter()
#IBOutlet weak var JTC: JTAppleCalendarView!
override func viewDidLoad() {
super.viewDidLoad()
let d = Date()
var dateArr = [Date]()
dateArr.append(d)
JTC.scrollToDate(Date())
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: JTAppleCalendarViewDelegate,JTAppleCalendarViewDataSource{
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let startDate = formatter.date(from: "2017 01 01")!
let endDate = formatter.date(from: "2117 12 31")!
let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
return parameters
}
func calendar(_ calendar:JTAppleCalendarView,cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell{
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell
cell.dateLabel.text = cellState.text
return cell
}
}
Thanks

The issue was solved for me by adding three methods in ViewDidLoad and setting start and end dates as follows:
override func viewDidLoad() {
self.calendarView.visibleDates {[unowned self] (visibleDates: DateSegmentInfo) in
self.setupViewsOfCalendar(from: visibleDates)
}
self.calendarView.scrollToDate(Date(),animateScroll: false)
self.calendarView.selectDates([ Date() ])
}
In Calendar configuration set dates as follows:
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
formatter.dateFormat = "yyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
var dateComponent = DateComponents()
dateComponent.year = 1
let startDate = Date()
let endDate = Calendar.current.date(byAdding: dateComponent, to: startDate)
let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate!, numberOfRows: 6, calendar: Calendar.current, generateInDates: .forFirstMonthOnly, generateOutDates: .off, firstDayOfWeek: .sunday, hasStrictBoundaries: true)
return parameters
}

Related

How to show Current Week in JTAppleCalendar in swift

for calendar i am using JTAppleCalendar pod in my project
and i am able to show current month in calendar, but i need to show current week in calendar but how
for current month showing in calendar am using below code
extension ViewController: JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
let startDate = formatter.date(from: "2010 01 01")!
let endDate = formatter.date(from: "2050 01 01")!
return ConfigurationParameters(startDate: startDate, endDate: endDate)
}
}
extension ViewController: JTAppleCalendarViewDelegate {
func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "dateCell", for: indexPath) as! DateCell
self.calendar(calendar, willDisplay: cell, forItemAt: date, cellState: cellState, indexPath: indexPath)
if testCalendar.isDateInToday(date) {
cell.dateLabel.textColor = UIColor.blue
cell.dateLabel.font = UIFont.boldSystemFont(ofSize: 13.0)
} else {
testCalendar.isDateInToday(date) == false
}
return cell
}
func calendar(_ calendar: JTAppleCalendarView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTAppleCollectionReusableView {
let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: "DateHeader", for: indexPath) as! DateHeader
formatter.dateFormat = "MMM yyyy"
header.monthTitle.text = formatter.string(from: range.start)
return header
}
}
0/p:
but i need to show current week in calendar, how?, plz do help
Return '1' for numberOfRows and modify the configureCalendar like this:
extension ViewController: JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy MM dd"
let startDate = formatter.date(from: "2010 01 01")!
let endDate = formatter.date(from: "2050 01 01")!
return ConfigurationParameters(startDate: startDate,
endDate: endDate,
numberOfRows: 1,
generateInDates: .forFirstMonthOnly,
generateOutDates: .off,
hasStrictBoundaries: false)
}
}
Following cocoapod match your requirement :
FSCalender
Please try to use below pod in pod file:
use_frameworks!
target '<Your Target Name>' do
pod 'FSCalendar'
end

Getting the "does not conform to JTAppleCalendarViewDelegate" error even when delegate method implemented

This is the entire extension section of the JTAppleCalendar delegate and datasource methods implementation.
extension ViewController : JTAppleCalendarViewDelegate, JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
// set date formatter
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let startDate = Date()
let endDate = (Calendar.current as NSCalendar).date(byAdding: .day, value: 180, to: startDate, options: [])!
let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
return parameters
}
func calendar(_ calendar: JTAppleCalendarView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTAppleCell {
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: "DateCell", for: indexPath) as! AccountsDateCell
cell.dateLabel.text = cellState.text
return cell
}
}
Xcode is saying:
Type 'ViewController' does not conform to protocol 'JTAppleCalendarViewDelegate'
It looks like the problem is with manual installation of the library. I dragged and dropped the files into this project. Is there any other way to manually add the library to the project?
You must implement the configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters delegate method.
If you are using Xcode 9, it should offer to insert the required function stubs for you.

Why can't I use JTAppleCalendar Pod File JTAppleCell in Swift 3?

I am using a JTAppleCalendar pod file in my project and when I installed the pod file I couldn't use the method JTAppleCell and I just could use JTAppleDayCell I watched this video
https://www.youtube.com/watch?v=Qd_Gc67xzlw
and this
https://www.youtube.com/watch?v=zOphH-h-qCs
Here is my codes
import UIKit
import JTAppleCalendar
class calendarViewController: UIViewController {
#IBOutlet weak var calendarCollectionView: UICollectionView!
let formatter = DateFormatter()
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension calendarViewController : JTAppleCalendarViewDataSource {
func configureCalendar(_ calendar: JTAppleCalendarView) -> ConfigurationParameters {
formatter.dateFormat = "yyyy MM dd"
formatter.timeZone = Calendar.current.timeZone
formatter.locale = Calendar.current.locale
let startDate = formatter.date(from: "2017 01 01")!
let endDate = formatter.date(from: "2017 12 31")!
let parameters = ConfigurationParameters(startDate: startDate, endDate: endDate)
return parameters
}
func calendar(_calebdar : JTAppleCalendarView , cellForItemAt date : Date , cellState : CellState , indexPath : IndexPath ) -> JTAppleDayCell {
let cell = calendarCollectionView.dequeueReusableCell(withReuseIdentifier: "JTCustomCell", for: indexPath) as! JTCustomCell
cell.dateLabel.text = cellState.text
return cell
}
}
If you are only able to use JTAppleDayCell instead of JTAppleCell, then you are on the wrong version of the library. That video showed you for version 7.0
So the question I ask now is what version are you using?
put this in your podfile:
pod 'JTAppleCalendar'
Then go to your console and run pod update.
The version should say 7.0.4 (which is the latest version as of this date).
If it is saying some other version, then you're doing something wrong.

Calculating Age From Date Picker Swift 3

In my code below i have implemented a date picker to be the subview of my textfield. I am stuck on the function; 'verifyAge'. The if statement in the function is working fine and will change the textField colour when the Date Picker date is above or below the specified date. But it only works to the corresponding year But does not Work to the exact Day. I have tried searching for the past two days and couldn't find a solution to my exact problem.
class AgeConfirmViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var txtAgeConfirmation: UITextField!
let datePicker: UIDatePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
txtAgeConfirmation.delegate = self
createDatePicker()
}
func textFieldDidBeginEditing(_ textField: UITextField) {
txtAgeConfirmation.inputView = datePicker
datePicker.addTarget(self, action: #selector(self.datePickerChanged(sender:)), for: .valueChanged)
}
func datePickerChanged(sender: UIDatePicker) {
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .long
txtAgeConfirmation.text = formatter.string(from: sender.date)
verifyAge()
}
func createDatePicker() {
datePicker.datePickerMode = .date
datePicker.maximumDate = Calendar.current.date(byAdding: .year, value: 0, to: Date())
}
func verifyAge() {
let dateOfBirth = datePicker.date
let today = Date()
let gregorian = NSCalendar(identifier: NSCalendar.Identifier.gregorian)
let age = gregorian?.components([.month, .day, .year], from: dateOfBirth, to: today, options:[])
if (age?.year)! < 21 {
txtAgeConfirmation.textColor = UIColor.red
} else if (age?.year)! > 21 {
txtAgeConfirmation.textColor = UIColor.black
}
}
Simple solution, ignore day and month:
let gregorian = Calendar(identifier: .gregorian)
let ageComponents = gregorian.dateComponents([.year], from: dateOfBirth, to: Date())
let age = ageComponents.year!
txtAgeConfirmation.textColor = age < 21 ? .red : .black
Or if you want to ignore the time
let ageComponents = calendar.dateComponents([.year], from: calendar.startOfDay(for: dateOfBirth), to: calendar.startOfDay(for: Date()))
In Swift 3 there are less question and exclamation marks by using native Calendar struct.
The age exclamation mark after year is absolutely safe because the year component is clearly specified.

Getting the difference in two dates - Swift

I cannot get the date difference function to work. It says NSDate is not implicitly convertible to 'Date' but I do not see an immediate work around this; using as Date does not work.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var dateLabelOutlet: UILabel!
let currentDate = NSDate()
let dateFormatter = DateFormatter()
let userCalendar = NSCalendar.current
let requestedComponent: NSCalendar.Unit = [
NSCalendar.Unit.month,
NSCalendar.Unit.day,
NSCalendar.Unit.hour,
NSCalendar.Unit.minute,
NSCalendar.Unit.second,
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func printTime(){
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss a"
let startTime = NSDate()
let endTime = dateFormatter.date(from: "25/12/16 00:00:00")
let timeDifference = userCalendar.components(requestedComponent, from: startTime, to: endTime!, options: [])
dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Change all of your NSDate to Date, then replace your requestedComponent with this:
let requestedComponent: Set<Calendar.Component> = [ .month, .day, .hour, .minute, .second]
Your difference will be:
let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
FYI: Your dateFormatter doesn't work with this "25/12/16 00:00:00"
here is your whole class in correct form:
class ViewController: UIViewController {
#IBOutlet weak var dateLabelOutlet: UILabel!
let currentDate = Date()
let dateFormatter = DateFormatter()
let userCalendar = Calendar.current
let requestedComponent: Set<Calendar.Component> = [.month,.day,.hour,.minute,.second]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func printTime() {
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
let startTime = Date()
let endTime = dateFormatter.date(from: "25/12/16 00:00:00")
let timeDifference = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
dateLabelOutlet.text = "\(timeDifference.month) Months \(timeDifference.day) Days \(timeDifference.minute) Minutes \(timeDifference.second) Seconds"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I think it will be helpfull.It will print all months between from and two dates
let dateFormtter = DateFormatter()
dateFormtter.dateFormat = "yyyy-MM-dd"
let startDate = dateFormtter.date(from: fromTF.text!)
let endDate = dateFormtter.date(from: toTF.text!)
func getMonthAndYearBetween(from start: String, to end: String) - >
[String] {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
guard let startDate = format.date(from: start),
let endDate = format.date(from: end) else {
return []
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(Set([.month,.day]),
from: startDate, to: endDate)
var allDates: [String] = []
let dateRangeFormatter = DateFormatter()
dateRangeFormatter.dateFormat = "yyyy-MM-dd"
for i in 0 ... components.month! {
guard let date = calendar.date(byAdding: .month , value: i, to: startDate) else {
continue
}
let formattedDate = dateRangeFormatter.string(from: date)
allDates += [formattedDate]
print(allDates)
}
return allDates
}
Call above method like this
print(getMonthAndYearBetween(from: fromTF.text!, to:
toTF.text!))

Resources