简体   繁体   English

如何将今天的日期与 Swift 中的另一个日期进行比较?

[英]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.通过将今天的日期与事件发生的日期与 function 进行比较,我想检查事件日期是否已过。

    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.我为此检查编写了 function,但即使日期已过,它也会返回 false。 What could be the reason for this?这可能是什么原因?

  • getDayMonDateFormat() function is return String getDayMonDateFormat() function 是返回字符串

Date objects are Comparable. Date对象是可比较的。 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.最好将服务器的开始日期加载为 Unix 纪元时间的数字偏移量。 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.如果您必须将服务器开始日期加载为字符串,请使用包含与 UTC 的偏移量的“Internet 日期字符串”。 Convert your input date string into a Date , and then just use code like if Date() > serverStartDate .将您的输入日期字符串转换为Date ,然后使用if Date() > serverStartDate类的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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