Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Get next date

Tags:

xcode

ios

swift

I am trying to write a function that takes a string (in the format "dd MM yyyy") and returns the day after the one given as a parameter.

For example:

let nextDay = getNextDay("31 12 2016")
print(nextDay)

Would print:

01 01 2017

Can someone show me how to do this? Thanks

like image 662
JordanW Avatar asked Dec 11 '22 12:12

JordanW


2 Answers

Here is the code snippet that may help you.

//Call method like this

convertNextDate(dateString: "31 12 2016")


// Method is here

func convertNextDate(dateString : String){    
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MM yyyy"
    let myDate = dateFormatter.date(from: dateString)!
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
    let somedateString = dateFormatter.string(from: tomorrow!)
    print("your next Date is \(somedateString)")
}

Another way is to create extension and here it is.

extension String {
    func convertToNextDate(dateFormat: String) -> String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = dateFormat
        let myDate = dateFormatter.date(from: self)!
        let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
        return dateFormatter.string(from: tomorrow!)
    }
}

Usage

print("31 12 2016".convertToNextDate(dateFormat: "dd MM yyyy"))

Note: You can use use your desired date-format just make sure it is appropriate.

like image 175
Maulik Pandya Avatar answered Dec 30 '22 09:12

Maulik Pandya


class DateHelper
{

  lazy var formatter:DateFormatter = {
  let formatter = DateFormatter()
  formatter.dateFormat = "dd MM yyyy"
  return formatter
}()

  lazy var dateComponents:DateComponents = {
  var dateComp = DateComponents()
  dateComp.day = 1
  return dateComp
}()

  func getNext(dateString:String) -> String?
  {
    if let date     =  self.formatter.date(from: dateString),
       let nextDate = Calendar.current.date(byAdding: self.dateComponents, to: date)
    {
      return self.formatter.string(from: nextDate)
    }
    return nil
  }
}

DateHelper().getNext(dateString: "31 12 2016")
like image 25
Vignesh Avatar answered Dec 30 '22 09:12

Vignesh