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
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With