且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Swift将字符串转换为日期输出错误的日期

更新时间:2022-11-30 23:25:13

你需要明白Date不仅代表一个日期,还代表一个时间.

You need to understand that Date does not only represent a date, but also a time.

>= 比较 Date 对象的日期和时间分量.由于您没有在日期字符串中指定任何时间,因此 API 假定它是您当地时间的 00:00:00,即 UTC 前一天的 18:30:00.你问为什么是UTC?这就是日期的description.打印日期时,它始终以 UTC 时间打印.要在您的时区打印它,请设置日期格式化程序的 timeZone 属性并对其进行格式化.

>= compares both date and time components of a Date object. Since you didn't specified any time in your date string, the API assumed it to be 00:00:00 in your local time, which is 18:30:00 of the previous day in UTC. Why UTC, you ask? That's what the description of the date always is. When you print a date, it always prints it in UTC time. To print it in your time zone, set the timeZone property of your date formatter and format it.

仅比较日期组件的一种方法是删除时间组件.从这个答案,这是您如何删除时间组件:

One way to only compare the date components is by removing the time components. From this answer, this is how you remove time components:

public func removeTimeStamp(fromDate: Date) -> Date {
    guard let date = Calendar.current.date(from: Calendar.current.dateComponents([.year, .month, .day], from: fromDate)) else {
        fatalError("Failed to strip time from Date object")
    }
    return date
}

现在应该是这样:

dateStartDate >= removeTimeStamp(fromDate: dateToday)