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

时间:2018-02-28 07:08:32

标签: ios swift date swift3

我想将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?")
}

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

4 个答案:

答案 0 :(得分:2)

您需要了解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)

答案 1 :(得分:1)

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

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

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

如果dateStartDate相同或更晚,则会打印“是” 那天比dateToday

比较方法返回.orderedAscending.orderedSame, 或.orderedDescending,具体取决于第一个日期是否开始 前一天,同一天或晚些时候,而不是第二天。

答案 2 :(得分:0)

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

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?")
}

答案 3 :(得分:-1)

timeZone

需要dateFormatter
dateFormatter.timeZone = TimeZone(secondsFromGMT:0)!
相关问题