Search code examples
iosswiftdateformatter

Date formating, adding days to date


Here is my first question;

import Foundation 

let date1 = Date()
let date2 = Date().addingTimeInterval(3600)

if date1 == date2
{
          print("equals")
}
else if date1 > date2
{
          print("date1 is bigger")
}
else if date1 < date2
{
          print("date2 is bigger")
}

It gives below output if i write print("date1") or print("date2")

2018-09-10 08:56:49 +0000

I would like to write the same example but date1 and date2 must include these 2 properties:

format: "dd.MM.yyyy"

locale: "tr_TR"

Beside this, here is my second question:

let date2 = Date().addingTimeInterval(3600)

As you know, this 3600 value adding an hour. How can I add one day? 24*3600? Is there any shortest way?


Solution

  • Like @Larme said, you might want to look into Calendar.

    var dateComponents = DateComponents()
    dateComponents.day = 1
    guard let date = Calendar.current.date(byAdding: dateComponents, to: Date()) else {  // Adding date components to current day.
       fatalError("date not found")
    }
    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .short // dd.MM.yyyy
    dateFormatter.locale = Locale(identifier: "tr_TR") // Your preferred locale
    let dateWithLocale = dateFormatter.string(from: date)
    print(date)
    

    Your comparison can be done using the Date objects. Only when you need to print it or use it as a String, you would need to do formatting.