【问题标题】:Swift convert string to date output wrong dateSwift将字符串转换为日期输出错误的日期
【发布时间】:2018-02-28 07:08:32
【问题描述】:

我想将 dateStartString = “28/02/2018” 转换为 Date 并将转换后的日期与今天的日期进行比较。当我转换dateStartString 时,转换后的日期是"2018-02-27 18:30:00 UTC"。为什么它的输出是错误的日期?

这是我的代码

var dateStartString = "28/02/2018"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
    fatalError("ERROR: Date conversion failed due to mismatched format.")
}

let dateToday = Date()

if(dateStartDate>=dateToday){
    print("Yes")
}
else{
    print("Today date is 28/02/2018. Why it print No?")
}

希望你能理解我的问题。 提前致谢。

【问题讨论】:

  • 你在哪个时区?

标签: ios swift date swift3


【解决方案1】:

您需要了解Date 不仅代表日期,还代表时间

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

仅比较日期组件的一种方法是删除时间组件。从此answer 中,您可以通过以下方式删除时间组件:

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)

【讨论】:

  • 谢谢。我明白了。它工作正常
【解决方案2】:

由于Sweeper explained, dateStartDate 位于00:0028/02/2018, 而dateToday 是当前时间点,即 在同一天,但午夜之后。因此dateStartDate >= dateToday 的计算结果为false

仅将时间戳与日期粒度进行比较并忽略 您可以使用的时间组件

if Calendar.current.compare(dateStartDate, to: dateToday, toGranularity: .day) != .orderedAscending {
    print("Yes")
}

如果dateStartDate 位于同一位置或更高版本上,这将打印“是” 比dateToday.

比较方法返回.orderedAscending.orderedSame、 或.orderedDescending,取决于第一次约会是否在 比第二个日期早一天、同一天或晚一天。

【讨论】:

    【解决方案3】:

    在映射日期时尝试设置您当前的日期格式化程序。 在您的示例代码更新下方:

    var dateStartString = "28/02/2018"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd/MM/yyyy"
    dateFormatter.locale = NSLocale.current
    guard let dateStartDate = dateFormatter.date(from: dateStartString) else {
        fatalError("ERROR: Date conversion failed due to mismatched format.")
    }
    
    var dateToday = Date()
    print(dateToday)
    let dateTodaystr = dateFormatter.string(from: dateToday)
    dateToday = dateFormatter.date(from: dateTodaystr)!
    print(dateToday)
    
    if(dateStartDate>=dateToday){
        print("Yes")
    }
    else{
        print("Today date is 28/02/2018. Why it print No?")
    }
    

    【讨论】:

      【解决方案4】:

      您需要timeZone 为您的dateFormatter

      dateFormatter.timeZone = TimeZone(secondsFromGMT:0)!
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 2011-11-28
        相关资源
        最近更新 更多