简体   繁体   中英

How can I compare today's date with another date in Swift?

By comparing today's date with the date that event will be with a function, I want to check if the event date has passed.

    func isEventPast() -> Bool? {
       let utc = eventDetailModel?.utcTimezone?.utc ?? ""
       let startTimeLocal: String = serverToLocal(dateStr: eventDetailModel?.startTime ?? "", timezone: utc) ?? ""
       return Date() > startTimeLocal.getDayMonDateFormat() ? true : false
    }

I wrote a function for this check, but it returns false even if the date has passed. What could be the reason for this?

  • getDayMonDateFormat() function is return String

Date objects are Comparable. You can use expressions like “=“, “>”, and “<“ on them directly.

If you want to know if a date has passed, just compare them as dates. Do not muck with date Formatters, time zones, or any of that.

It's best if you can load your server's start date as a numeric offset from the Unix Epoch time. Then you can avoid date string conversions, time zones, etc.

If you must load your server start date as a string, use an “Internet date string” that includes an offset from UTC. Convert your input date string into a Date , and then just use code like if Date() > serverStartDate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM