首页 > 解决方案 > 如何在 Calendar.current.isDateInToday 中考虑时区?

问题描述

我使用返回日期字符串的 API,例如2021-05-05T23:00:00+00:00. 然后我将其转换为 Swift Date 对象,并尝试使用 Calendar.current 检查日期是今天还是明天。

    let apiDate = "2021-05-05T23:00:00+00:00";
    let dateFormatter = ISO8601DateFormatter()
    let myDate = dateFormatter.date(from: apiDate)!
    
    if Calendar.current.isDateInToday(myDate) {
         print("Date is today") // this should be true
    } else if Calendar.current.isDateInTomorrow(myDate) {
         print("Date is tomorrow") // this is true instead
    } else {
         print("Date is not today or tomorrow")
    }

问题是isDateInToday应该是true。出于某种原因,它在检查是否是今天并且返回时添加了我的时区(+3 小时)false。我怎样才能使我得到基于电话当地时间的结果?

标签: iosswift

解决方案


推荐阅读