【问题标题】:Changing the TimeZone of FSCalendar Globally in the project在项目中全局更改 FSCalendar 的时区
【发布时间】:2020-02-19 17:48:23
【问题描述】:

我正在开展一个列出不同项目位置的项目,每个项目位置都与不同的时区相关联。我正在使用 FSCalendar 在其时区显示当前选定项目的日期。我无法在 FSCalendar 视图上正确显示日期。

我想在 FSCalendar 视图上显示日期,而与设备中配置的时区无关。这意味着即使用户手动更改时区以在设备中设置,此更改也不应该影响我的项目日历。 (例如:通常在所有设备中都会选择自动时区)

要实现这一点,我必须使用选定的项目时区配置 FSCalendar。

我尝试使用 DateFormatter() 将 Date() 转换为 Project 时区。 尝试过 DST 计算。

  func isDateInProjectTimeZone() -> Bool {
       if let projectTimeZone = AppUtils.timeZoneForProject() {
           let dateFormatter = DateFormatter()
           dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

           var calendar = Calendar.current
           calendar.timeZone = projectTimeZone

           return calendar.isDateInToday(Date().dateInProjectTimeZone())
       }
       return false
  }

【问题讨论】:

    标签: ios swift timezone fscalendar


    【解决方案1】:

    我刚刚遇到了同样的问题,并通过更新项目本身解决了它。

    1. 通过从FSCalendar.m 删除属性并将其添加到FSCalendar.h 来公开时区:
    @property (copy, nonatomic) NSTimeZone *timeZone;
    
    1. 覆盖设置器:
    - (void)setTimeZone:(NSTimeZone *)timeZone
    {
        if (![_timeZone isEqual:timeZone]) {
            _timeZone = timeZone.copy;
            [self invalidateDateTools];
        }
    }
    

    【讨论】:

      【解决方案2】:

      我能够使用 FSCalendar 通过以下步骤实现我的要求,如果有人遇到相同的情况,答案可能会有用。

      要更改 FSCalendar 时区,请按照以下步骤操作:

      • 创建一个自定义的 FSCalendar 类并编写所需的初始化方法,如下所示。

        import FSCalendar
        
        class XYZFSCalendar: FSCalendar {
        
           override init(frame: CGRect) {
              super.init(frame: frame)
           }
        
           required init?(coder aDecoder: NSCoder) {
        
               super.init(coder: aDecoder)
        
               if let projectTimeZone = <Set_Your_Time_Zone_Here> {
                  self.setValue(projectTimeZone, forKey: "timeZone")
                  self.perform(Selector(("invalidateDateTools")))
               }
           }
        }
        
      • 以上代码使FSCalendar独立于系统时间

      • 将 Storyboard 中的上述自定义日历指定为 FSCalendar 的自定义类
      • 如果您将任何日期分配给日历

      例如:

      import FSCalendar
      
      class ViewController: UIVIewController {
          @IBOutlet weak var calendar: XYZFSCalendar!
      
          override func viewDidLoad() {
             super.viewDidLoad()
      
             //When you set the date below, the date will be displayed in the FSCalendar based on your custom timezone.
             calendar.select = Date()
      
          }
      } 
      

      这对我的方案有所帮助,希望它也可以帮助有需要的人。 timeZone 可能不会全局更改,但每次使用您为 FSCalendar 预设的 timeZone 实例化类时,它都会起作用。

      谢谢。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-28
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 2019-01-25
        • 2011-04-18
        • 1970-01-01
        • 2018-09-29
        相关资源
        最近更新 更多