Swift convert string to date output wrong date

和自甴很熟 提交于 2021-02-10 13:24:24

问题


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?

here is my code

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.


回答1:


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

>= 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
}

Now this should be true:

dateStartDate >= removeTimeStamp(fromDate: dateToday)



回答2:


As Sweeper explained, dateStartDate is at 00:00 of 28/02/2018, whereas dateToday is the current point in time, which is on the same day, but after midnight. Therefore dateStartDate >= dateToday evaluates to false.

To compare the timestamps only to day granularity and ignore the time components you can use

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

This will print "Yes" if dateStartDate is on the same or a later day than dateToday.

The compare method returns .orderedAscending, .orderedSame, or .orderedDescending, depending on wether the first date is on a previous day, the same day, or a later day, than the second date.




回答3:


try to set your current date Formatter while comapring date. Below your sample code update:

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:


You need to timeZone for your dateFormatter:

dateFormatter.timeZone = TimeZone(secondsFromGMT:0)!


来源:https://stackoverflow.com/questions/49023814/swift-convert-string-to-date-output-wrong-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!