为什么在转换日期和获取当前日期时会出现时区差异?

Why am I getting timezone differences when converting date and getting current date?

在下面的代码示例中:

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
}

我没有看到正确的日期。我花了 4 个小时尝试各种选项,但一直回到相同的输出。如何查看下面的预期输出?

我期待看到以下内容:

    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)))

有趣的是,我位于阿德莱德,时间是22:20(晚上10:20)。为什么调用 Date() 时时间不同?

 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
}

试试这个。您试图将字符串转换为日期。为了获得该格式,您应该更改它所需的字符串格式。