Search code examples
iosstringdateswift4nsdateformatter

Date from String is not giving correct date


I want to set "EST" as the default time zone for every user, but there is one condition that needs to be check in the current date at 7:45 PM. So I am comparing two dates, but the problem is when I convert the current Date to String it gives me the correct EST time, when I convert that String again to Date in EST it gives me time 4 hours ahead of EST. Here is the code for conversion

class func getCurrentDateTime() -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone(abbreviation: "EST")
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    let dateString = dateFormatter.string(from: Date())
    print(dateString)

    let convertDateFormatter = DateFormatter()
    convertDateFormatter.dateFormat = "dd-MM-yyyy"
    convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
    let currentDate = convertDateFormatter.string(from: Date())
    print(currentDate)

    let comparedDateFormatter = DateFormatter()
    comparedDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    comparedDateFormatter.timeZone = TimeZone(abbreviation: "EST")
    let comparedDate = comparedDateFormatter.date(from: "\(currentDate) 19:45:00")
    print(comparedDate)

    let currentDateFormatter = DateFormatter()
    currentDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
    comparedDateFormatter.timeZone = TimeZone.init(abbreviation: "EST")
    let currentDateAndTime = currentDateFormatter.date(from: dateString)
    print(currentDateAndTime)

    return dateString

}


Solution

  • So a date does not have a time zone. So when I use a dateFormatter to convert a date to a string representation of the string will reflect the time zone the dateFormatter is set to. But when you use the same formatter to convert the the string back into a date the date would not have the the time zone offset anymore. So this sounds to me as if it is working properly.

    Edit: So if you are trying to compare two dates I would do something like:

    let date1 = Date()
    let date2 = Date().addingTimeInterval(100)
    
    if date1 == date2 {
       // dates are exactly equal
    } else if date1 > date2 {
      // date1 is the most recent
    } else if date1 < date2 {
      // date2 is the most recent
    }
    

    And if I were trying to display these dates I would use the date formatter to convert them to strings.