从每个月算起第1天

时间:2017-12-02 00:53:21

标签: ios swift

我正在尝试制作一个计数器,计算每个月的第1天,并在下个月达到特定日期时自行重置。

这是我的代码:

    let date = NSDate()
    let calendar = Calendar.current

    let currentDate = calendar.date(from: components)

    let userCalendar = Calendar.current

    // here we set the due date. When the timer is supposed to finish
    let competitionDate = NSDateComponents()

    competitionDate.year = components.year!
    competitionDate.month = components.month!

    competitionDate.day = 9
    competitionDate.hour = 00
    competitionDate.minute = 00
    let competitionDay = userCalendar.date(from: competitionDate as DateComponents)!

    //here we change the seconds to hours,minutes and days
    let CompetitionDayDifference = calendar.dateComponents([.day, .hour, .minute], from: Date().startOfMonth(), to: competitionDay)

    //finally, here we set the variable to our remaining time
    let daysLeft = CompetitionDayDifference.day
    let hoursLeft = CompetitionDayDifference.hour
    let minutesLeft = CompetitionDayDifference.minute

    print(daysLef)
    counter.value = CGFloat(daysLeft!)

此代码的问题是,当它到达第0天时,它从未将自身重置为从当前日期到下个月第9天的计数

1 个答案:

答案 0 :(得分:1)

您应该使用日历方法using (StreamReader sr = new StreamReader("maybyourfilepat\data.csv")) { string line = sr.ReadLine(); //incase if you want to ignore the header while (line != null) { string[] strCols = line.Split(','); line = sr.ReadLine(); } } ,将日期日期组件传递给它,使用matchingPolicy cdvfile://,repeatedTimePolicy func nextDate(after date: Date, matching components: DateComponents, matchingPolicy: Calendar.MatchingPolicy, repeatedTimePolicy: Calendar.RepeatedTimePolicy = default, direction: Calendar.SearchDirection = default) -> Date?和方向.strict来查找下一个日期。然后你只需要使用Calendar方法.first并传递你想要返回的日期组件(日,小时,分钟):

.forward

用法:

func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents