Swift将字符串转换为日期输出错误的日期 [英] Swift convert string to date output wrong date

查看:23
本文介绍了Swift将字符串转换为日期输出错误的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to convert dateStartString = "28/02/2018" in to Date and compare that converted date with today date. when i convert dateStartString the converted date is "2018-02-27 18:30:00 UTC".why its output is wrong date?

这是我的代码

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

希望你明白我的问题.提前致谢.

Hope you understand my problem. Thanks in advance.

推荐答案

你需要明白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)

这篇关于Swift将字符串转换为日期输出错误的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆