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!))
Related
I have two components in my app. A UIDATEPICKER that is set to select the time only, HOURS AND MINUTES. and A calendar (FSCALENDAR 3rd party) that selects the date,month and year for me. I am trying to combine the time selected from a uidatepicker and the date selected from the calendar to create a notification. it is working so far but the hour is 5 hours ahead. i think it is because of the 12 hour format of the uidatepicker. how do i extract the hour component in 24 hours format?
The code below is for extracting the date and time.
class ReminderViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource {
var reminderDate : String?
var reminderDay : Int?
var reminderMonth : Int?
var reminderYear : Int?
var reminderHour : Int?
var reminderMinute : Int?
#IBOutlet weak var rDatePicker: UIDatePicker!
#IBAction func reminderDatePicker(_ sender: Any) {
var df = DateFormatter()
let date = rDatePicker.date
let dateAsString = df.string(from: date)
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
reminderHour = components.hour!
reminderMinute = components.minute!
}
#IBOutlet weak var doneButton: UIButton!
#IBAction func doneAction(_ sender: Any) {
let calendar = Calendar.current
let totalComponents = NSDateComponents()
totalComponents.day = reminderDay!
totalComponents.hour = reminderHour!
totalComponents.month = reminderMonth!
totalComponents.minute = reminderMinute!
totalComponents.year = reminderYear!
let finalDate = calendar.date(from: totalComponents as DateComponents)
print(finalDate)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.widthAnchor.constraint(equalToConstant: 500).isActive = true
reminderCalendar.delegate = self
reminderCalendar.dataSource = self
let totalComponents = NSDateComponents()
let calendar = Calendar.current
let date = Date()
let components = Calendar.current.dateComponents([.hour, .minute, .month, .day , .year], from: date)
reminderHour = components.hour!
reminderMinute = components.minute!
reminderMonth = components.month!
reminderDay = components.day!
reminderYear = components.year!
let finalDate = calendar.date(from: components as DateComponents)
print("FINAL" , finalDate)
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
print(date)
var df = DateFormatter()
df = DateFormatter()
df.dateFormat = "dd-MM-yyyy"
reminderDate = df.string(from: date)
reminderMonth = Calendar.current.component(.month, from: date)
reminderDay = Calendar.current.component(.day, from: date)
reminderYear = Calendar.current.component(.year, from: date)
print(reminderMonth)
print(reminderYear)
print(reminderDay)
}
}
Get a date and time and Convert it in UST format based on your timezone you are ahead that's why it create issue
func localToUTC(date:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.calendar = NSCalendar.current
dateFormatter.timeZone = TimeZone.current
let dt = dateFormatter.date(from: date)
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.string(from: dt!)
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
print(date)
var df = DateFormatter()
df = DateFormatter()
df.dateFormat = "yyyy:MM:dd:HH:mm:ss"
reminderDate = df.string(from: date)
reminderMonth = Calendar.current.component(.month, from: date)
reminderDay = Calendar.current.component(.day, from: date)
reminderYear = Calendar.current.component(.year, from: date)
print(reminderMonth)
print(reminderYear)
print(reminderDay)
}
I have Date() properties. startingAt and endingAt. And an array of Date(), which are alreadyRegistred. I have to create an array of strings with dates between startingAt and endingAt. StartingAt and endingAt are included and the last requirement is to exclude alreadyRegistred dates.
Do you have some elegant idea, how to do it? Thanks for help!
Edit: Maximum number of dates in final array will be about 7 days.
Dont forget that a Date is basically just a timestamp, and that you can have access to the addingTimeInterval(_:) method.
Knowing that, is very easy to do some calculation between two dates.
I do not have the whole knowledge about your required business logic, but here is a naive implementation that generates Dates between two dates. I'm sure you can run it in a playground and explore a little bit.
import UIKit
func intervalDates(from startingDate:Date, to endDate:Date, with interval:TimeInterval) -> [Date] {
guard interval > 0 else { return [] }
var dates:[Date] = []
var currentDate = startingDate
while currentDate <= endDate {
currentDate = currentDate.addingTimeInterval(interval)
dates.append(currentDate)
}
return dates
}
let startingDate = Date() // now
let endDate = Date(timeIntervalSinceNow: 3600 * 24 * 7) // one week from now
let intervalBetweenDates:TimeInterval = 3600 * 3// three hours
let dates:[Date] = intervalDates(from: startingDate, to: endDate, with: intervalBetweenDates)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
let dateStrings = dates.map{dateFormatter.string(from: $0)}
print("NOW : \(startingDate)")
for (index, string) in dateStrings.enumerated() {
print("\(index) : \(string)")
}
print("END DATE : \(endDate)")
Try this and see:
// Start & End date string
let startingAt = "01/01/2018"
let endingAt = "08/03/2018"
// Sample date formatter
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
// start and end date object from string dates
var startDate = dateFormatter.date(from: startingAt) ?? Date()
let endDate = dateFormatter.date(from: endingAt) ?? Date()
// String date array, to be excluded
let alreadyRegistred = ["01/01/2018", "15/01/2018", "10/02/2018", "20/02/2018", "05/03/2018"]
// Actual operational logic
var dateRange: [String] = []
while startDate <= endDate {
let stringDate = dateFormatter.string(from: startDate)
startDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate) ?? Date()
if (alreadyRegistred.contains(stringDate)) {
continue
} else {
dateRange.append(stringDate)
}
}
print("Resulting Array - \(dateRange)")
Here is result:
Resulting Array - ["02/01/2018", "03/01/2018", "04/01/2018", "05/01/2018", "06/01/2018", "07/01/2018", "08/01/2018", "09/01/2018", "10/01/2018", "11/01/2018", "12/01/2018", "13/01/2018", "14/01/2018", "16/01/2018", "17/01/2018", "18/01/2018", "19/01/2018", "20/01/2018", "21/01/2018", "22/01/2018", "23/01/2018", "24/01/2018", "25/01/2018", "26/01/2018", "27/01/2018", "28/01/2018", "29/01/2018", "30/01/2018", "31/01/2018", "01/02/2018", "02/02/2018", "03/02/2018", "04/02/2018", "05/02/2018", "06/02/2018", "07/02/2018", "08/02/2018", "09/02/2018", "11/02/2018", "12/02/2018", "13/02/2018", "14/02/2018", "15/02/2018", "16/02/2018", "17/02/2018", "18/02/2018", "19/02/2018", "21/02/2018", "22/02/2018", "23/02/2018", "24/02/2018", "25/02/2018", "26/02/2018", "27/02/2018", "28/02/2018", "01/03/2018", "02/03/2018", "03/03/2018", "04/03/2018", "06/03/2018", "07/03/2018", "08/03/2018"]
let startDate = Date()
let endDate = Date().addingTimeInterval(24*60*60*10) // i did this to get the end date for now
var stringdateArray = [String]()
if let days = getNumberofDays(date1: startDate, date2: endDate) {
for i in 0...days-1 {
let date = startDate.addingTimeInterval(Double(i)*24*3600)
let stringDate = getStringDate(fromDate: date, havingFormat: "yyyy-MM-dd")
if !(alreadyRegisteredArray.contains(stringDate)) { // checking if already registered
stringdateArray.append(stringDate)
}
}
}
and our helper method
let dateFormatter = DateFormatter()
func getStringDate(fromDate: Date,havingFormat: String) -> String {
dateFormatter.dateFormat = havingFormat
dateFormatter.amSymbol = "AM"
dateFormatter.pmSymbol = "PM"
let date = dateFormatter.string(from: fromDate)
return date
}
func getNumberofDays(date1: Date, date2: Date) -> Int? {
let calendar = NSCalendar.current
let date1 = calendar.startOfDay(for: date1)
let date2 = calendar.startOfDay(for: date2)
let components = calendar.dateComponents([.day], from: date1, to: date2)
return components.day
}
How Can I convert dates into string format?
I am getting dates between two dates ( From to end date). and I was using this below method
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
print(fmt.string(from: startDate))
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}}
and printing dates here
Dates.printDatesBetweenInterval(Dates.dateFromString("2017-10-02"), Dates.dateFromString("2017-10-9"))
result:
2017-10-02 2017-10-03 2017-10-04 2017-10-05 2017-10-06 2017-10-07 2017-10-08 2017-10-09
Now, I want pass this dates to String format to calendar (I am using FSCalendar lib into app). I want this format
example:
["2017-10-02", "2017-10-03", "2017-10-04", "2017-10-05", "2017-10-06", "2017-10-07", "2017-10-08", "2017-10-09"]
Can anyone guide me . Thanks
static func getDatesStringBetweenInterval(_ startDate: Date, _ endDate: Date)-> String {
var retval = "["
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
while startDate <= endDate {
if startDate < endDate {
retval.append("\"\(fmt.string(from: startDate))\", ")
} else {
retval.append("\"\(fmt.string(from: startDate))\"")
}
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
retval.append("]")
return retval
}
Usage:
let aDate = Dates.dateFromString("2017-01-01")
let bDate = Dates.dateFromString("2017-01-05")
let datesString = Dates.getDatesStringBetweenInterval(aDate, bDate)
print(datesString)
Return date string array from your function, like this:
class Dates {
static func printDatesBetweenInterval(_ startDate: Date, _ endDate: Date) -> [String] {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
var arrayDateString = [String]()
while startDate <= endDate {
let stringDate = fmt.string(from: startDate)
print("stringDate - \(stringDate)")
arrayDateString.append(stringDate)
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return arrayDateString
}
static func dateFromString(_ dateString: String) -> Date {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
return dateFormatter.date(from: dateString)!
}}
Now, print string array
let dateStringArray = Dates.printDatesBetweenInterval(Dates.dateFromString("2017-10-02"), Dates.dateFromString("2017-10-9"))
print("dateStringArray - \(dateStringArray)")
Edit:
Now, as you said, you've data in following format:
let dataArray = [
{ "hlddate": "07-Aug", "frmdt": "07-Aug-2017", "todt": "07-Aug-2017" },
{ "hlddate": "15-Aug", "frmdt": "15-Aug-2017", "todt": "15-Aug-2017" },
{ "hlddate": "10-Oct", "frmdt": "10-Oct-2017","todt": "31-Oct-2017" }
]
Try with following solution (Copy-paste, dataAray and class structure and see result):
class Dates {
static func dateFromString(dateString: String, webResponseDateFormat: String = "yyyy-MM-dd") -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = webResponseDateFormat
return dateFormatter.date(from: dateString)
}}
static func printDatesBetweenInterval(startDate: Date, endDate: Date, requiredDateFormat: String = "yyyy-MM-dd") -> [String] {
var startDate = startDate
let calendar = Calendar.current
let fmt = DateFormatter()
fmt.dateFormat = requiredDateFormat
var arrayDateString = [String]()
while startDate <= endDate {
let stringDate = fmt.string(from: startDate)
print("stringDate - \(stringDate)")
arrayDateString.append(stringDate)
startDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
}
return arrayDateString
}
if let stringDateArray = dataArray as? [[String : String]] {
for arrayElement in stringDateArray {
if let startDateString = arrayElement["frmdt"], let startDate = Dates.dateFromString(dateString: startDateString, webResponseDateFormat: "dd-MMM-yyyy"), let endDateString = arrayElement["todt"], let endDate = Dates.dateFromString(dateString: endDateString, webResponseDateFormat: "dd-MMM-yyyy") {
let dateStringArray = Dates.printDatesBetweenInterval(startDate: startDate, endDate: endDate, )
print("\n\n**\ndateStringArray - \(dateStringArray)")
}
}
}
Final Update
// Actual data structure
let dataArray = ["07-8-2017","08-08-2017","10-09-2017","20-10-2017",21-10-2017","23-10-2017", etc..]
Use above method and change data in server response section and getting result.
if let Streams = jsonDict["data"] as! [AnyObject]? {
for arrayElement in Streams {
if let startDateString = arrayElement["frmdt"] {
self.somedateFromString = self.convertStringToDate(string: startDateString as! String)
if let endDateString = arrayElement["todt"] {
self.somedateEndString = self.convertStringToDate(string: endDateString as! String)
}
self.presentdays = Dates.printDatesBetweenInterval(Dates.dateFromString(self.somedateFromString), Dates.dateFromString(self.somedateEndString))
self.totalHolidays.append(contentsOf: self.presentdays)
}
}
}
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
}
I want to create a project where:
I create a task to do.
I create a stoping date for this task
I create three reminders using date picker
This I've done already. But now, I want the label to return for me the hour of the closest reminder (but I want the label to do this until the stoping date)
What I accomplish already is a playground project:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let currentDate = dateFormatter.dateFromString("2016-01-03 16:30")
var firstDate = dateFormatter.dateFromString("2016-01-03 13:00")
var secondDate = dateFormatter.dateFromString("2016-01-03 16:00")
var thirdDate = dateFormatter.dateFromString("2016-01-03 17:00")
var datesArray = [firstDate, secondDate, thirdDate]
let firstInterval = firstDate?.timeIntervalSinceDate(currentDate!)
let secondInterval = secondDate?.timeIntervalSinceDate(currentDate!)
let thirdInterval = thirdDate?.timeIntervalSinceDate(currentDate!)
let intervalArray = [firstInterval, secondInterval, thirdInterval]
var aboveZeroIntervals = [NSTimeInterval]()
for interval in intervalArray {
if interval > 0 {
aboveZeroIntervals.append(interval!)
}
}
//print(aboveZeroIntervals)
for date in datesArray {
if date?.timeIntervalSinceDate(currentDate!) == aboveZeroIntervals.minElement() {
print(dateFormatter.stringFromDate(date!))
}
}
How to get only hours from first/second/thirdDate and display the hour from those three dates that is the closest to currentDate hour? And perfectly finish displaying it after currentDate exceeds stopDoingDate...
I came up with something like this (code below). Can anyone look at it and tell me if there is some way I can simplify this?
extension NSDate
{
func isGreaterThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
{
isGreater = true
}
//Return Result
return isGreater
}
}
let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let currentDate = dateFormatter.dateFromString("2016-01-04 16:30")
let stopDoingDate = dateFormatter.dateFromString("2016-01-06 15:00")
if stopDoingDate!.isGreaterThanDate(currentDate!) {
let currentDateComponents = calendar.components([.Year, .Month, .Day, .Hour, .Minute], fromDate: currentDate!)
currentDateComponents.hour
currentDateComponents.minute
let dateTimeFormatter = NSDateFormatter()
dateTimeFormatter.dateFormat = "HH:mm"
let currentOnlyTime = dateTimeFormatter.dateFromString("\(currentDateComponents.hour):\(currentDateComponents.minute)")
var firstDate = dateFormatter.dateFromString("2016-01-03 13:00")
var firstDateComponents = calendar.components([.Hour, .Minute], fromDate: firstDate!)
var firstDateTime = dateTimeFormatter.dateFromString("\(firstDateComponents.hour):\(firstDateComponents.minute)")
var secondDate = dateFormatter.dateFromString("2016-01-03 16:00")
var secondDateComponents = calendar.components([.Hour, .Minute], fromDate: secondDate!)
var secondDateTime = dateTimeFormatter.dateFromString("\(secondDateComponents.hour):\(secondDateComponents.minute)")
var thirdDate = dateFormatter.dateFromString("2016-01-03 17:00")
var thirdDateComponents = calendar.components([.Hour, .Minute], fromDate: thirdDate!)
var thirdDateTime = dateTimeFormatter.dateFromString("\(thirdDateComponents.hour):\(thirdDateComponents.minute)")
var datesArray = [firstDateTime, secondDateTime, thirdDateTime]
let firstInterval = firstDateTime?.timeIntervalSinceDate(currentOnlyTime!)
let secondInterval = secondDateTime?.timeIntervalSinceDate(currentOnlyTime!)
let thirdInterval = thirdDateTime?.timeIntervalSinceDate(currentOnlyTime!)
let intervalArray = [firstInterval, secondInterval, thirdInterval]
var aboveZeroIntervals = [NSTimeInterval]()
for interval in intervalArray {
if interval > 0 {
aboveZeroIntervals.append(interval!)
}
}
//print(aboveZeroIntervals)
for date in datesArray {
if date?.timeIntervalSinceDate(currentOnlyTime!) == aboveZeroIntervals.minElement() {
let dateTime = calendar.components([.Hour, .Minute], fromDate: date!)
print(dateFormatter.dateFromString("\(currentDateComponents.year)-\(currentDateComponents.month)-\(currentDateComponents.day) \(dateTime.hour):\(dateTime.minute)")!)
print("Next todo hour is: \(dateTime.hour): \(dateTime.minute)")
}
}
} else {
print("Todo DONE")
}
I came up with this:
The only problem is to generate array of dates from currentDate to stopDoingDate but I will handle this alone (and probably post a solution here as well)
I used one of this forum post to generate extension to NSDate:
extension NSDate
{
func isGreaterThanDate(dateToCompare : NSDate) -> Bool
{
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
{
isGreater = true
}
//Return Result
return isGreater
}
}
//let calendar = NSCalendar.currentCalendar()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
let currentDate = dateFormatter.dateFromString("2016-01-04 14:00")!
let stopDoingDate = dateFormatter.dateFromString("2016-01-06 16:00")!
let date1 = dateFormatter.dateFromString("2016-01-04 09:00")
let date2 = dateFormatter.dateFromString("2016-01-04 15:00")
let date3 = dateFormatter.dateFromString("2016-01-05 09:00")
let date4 = dateFormatter.dateFromString("2016-01-05 15:00")
let date5 = dateFormatter.dateFromString("2016-01-06 09:00")
let date6 = dateFormatter.dateFromString("2016-01-06 15:00")
var dates: [NSDate] = [date1!, date2!, date3!, date6!, date5!, date4!]
if stopDoingDate.isGreaterThanDate(currentDate) {
var datesAfterCurrentDate = [NSDate]()
for date in dates {
if date.isGreaterThanDate(currentDate) {
datesAfterCurrentDate.append(date)
}
}
let sortedDatesAfterCurrentDate = datesAfterCurrentDate.sort({ $0.timeIntervalSince1970 < $1.timeIntervalSince1970 })
let dateToDisplay = sortedDatesAfterCurrentDate.first!
let timeFormatter = NSDateFormatter()
timeFormatter.timeStyle = .ShortStyle
print(timeFormatter.stringFromDate(dateToDisplay)) } else {
print("We are done here")
}
This forum is truly awesome! Thanks Leo Dabus for the simple idea!