如何跟踪随日期移动的数据?

时间:2017-06-10 18:47:28

标签: ios swift date userdefaults

我有一个学校应用程序,可以跟踪您的日程安排。该应用程序有多种输入计划的选项。如果用户有四天的时间表,那么他们将有A-D天。对于我的应用程序我想跟踪当前的情况(例如,它是否是A日与C日)。用户可以指定他们设置应用程序的日期,但应用程序应该每天跟踪此更改,减去周末。我不确定实现这个的最佳方法是什么。

2 个答案:

答案 0 :(得分:0)

如果配置允许完全任意的日期分配,则只需要[Date:String]形式的简单字典。

如果您想让您的用户指定日标识符(字母)的重复模式,配置参数和过程将需要更复杂,并取决于您愿意处理异常的程度(即非学校)天)。周末可以是自动的,但假期和预定的“休息日”将要求您定义某种规则(硬编码或用户可配置)。

在所有情况下,我建议创建一个函数,根据配置的参数将任何日期转换为日期标识符。根据规则的复杂程度和您使用的日期范围,动态构建日期标识符的全局字典(例如[Date:String])并且每个日期仅计算一次标识符可能是个好主意。

例如:

// your configuration parameters could be something like this:

let firstSchoolDay:Date     = // read from configuration
let lastSchoolDay           = // read from configuration
let dayIdentifiers:[String] = // read from configuration 
let skippedDates:Set<Date>  = // read from configuration 

// The global dictionary and function could work like this:

var dayIdentifiers:[Date:Sting] = [:] // global scope (or singleton)
func dayIdentifier(for date:Date) -> String
{
    if let dayID = dayIdentifiers[date]
    { return dayID  }

    let dayID:String = // compute your day ID once according to parameters.
                       // you could use an empty string as a convention for
                       // non school days

                       // a simple way to compute this is to start from
                       // the last computed date (or firstSchoolDay)
                       // and move forward using Calendar.enumerateDates
                       // applying the weekend and offdays rules
                       // and saving day identifiers as you
                       // move forward up to the requested date

    dayIdentifiers[date] = dayID
    return dayID         
}

答案 1 :(得分:0)

我想出了如何跟踪移动日期,同时也没有考虑周末和每次检查时更新值。

func getCurrentDay() -> Int {

    let lastSetDay = //Get the last value of the set day
    let lastSetDayDate = //Get the last time the day was set
    var numberOfDays: Int! //Calculate number of recurring days, for instance an A, B, C, D day schedule would be 4

    var currentDay = lastSetDay
    var currentIteratedDate = lastSetDayDate

    while Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
        currentIteratedDate = Calendar.current.date(byAdding: .day, value: 1, to: currentIteratedDate)!
        if !Calendar.current.isDateInWeekend(currentIteratedDate) {
            currentDay += 1
        }
        if currentDay > numberOfDays {
            currentDay = 1
        }
    }

    if Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
        //Save new day
        //Save new date
    }

    return currentDay
}