Home > Software design >  Why am I getting timezone differences when converting date and getting current date?
Why am I getting timezone differences when converting date and getting current date?

Time:12-22

In the following code example:

func numberOfDaysBetween(toDate: String) -> Int { // toDate = "2021/12/21"

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "yyyy/MM/dd"
    
    let currentDate = Date()
    let toDateFormatted = dateFormatter.date(from: toDate)
    
    print ("Current Date:     \(currentDate)")         // Current Date:     2021-12-21 11:50:12  0000
    print ("ToDate:           \(toDate)")              // ToDate:           2021/12/21
    print ("ToDateFormatted:  \(toDateFormatted)")     // ToDateFormatted:  Optional(2021-12-20 13:30:00  0000)
    print (dateFormatter.timeZone)                     // Optional(Australia/Adelaide (fixed (equal to current)))
    
    return 1 // Test value
}

I am not seeing correct dates. I have spent 4 hours trying various options, but keep coming back to the same output. How do I see the expected output below?

I am expecting to see the following:

    print ("Current Date:     \(currentDate)")         // Current Date:     2021-12-21
    print ("ToDate:           \(toDate)")              // ToDate:           2021/12/21
    print ("ToDateFormatted:  \(toDateFormatted)")     // ToDateFormatted:  2021/12/21
    print (dateFormatter.timeZone)                     // Optional(Australia/Adelaide (fixed (equal to current)))

Interestingly, I am located in Adelaide, and the time is 22:20 (10:20 PM). Why is the time different when calling Date()?

CodePudding user response:

 func numberOfDaysBetween(toDate: String) -> Int { // toDate = "2021/12/21"

    let dateFormatter = DateFormatter()
    dateFormatter.timeZone = TimeZone.current
    dateFormatter.dateFormat = "yyyy/MM/dd"
    
    let currentDate = Date()
    let toDateFormatted = dateFormatter.date(from: toDate)
    let df = dateFormatter.string(from: toDateFormatted!)
    
    print ("Current Date:     \(currentDate)")         // Current Date:     2021-12-21 11:50:12  0000
    print ("ToDate:           \(toDate)")              // ToDate:           2021/12/21
    print ("ToDateFormatted:  \(df)")     // ToDateFormatted:  Optional(2021-12-20 13:30:00  0000)
    print (dateFormatter.timeZone)                     // Optional(Australia/Adelaide (fixed (equal to current)))
    
    return 1 // Test value
}

try this . you were trying to convert the string to date. so that you got that format, you supposed to change it required string format.

  • Related