2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

今年が何割終了したかを Date() に教えてもらう

Posted at

2016年ももう95%は終わったようですねって簡単に言えるようなエクステンションを書きました。

必要だと思って書いたものの実はいらないってわかって…。とは言えせっかく書いたので勢いに任せて残しておきます。あんまりテストしてないのでバグがあったらごめんなさい。


// パーセント

extension Date {

    /// 今日が何パーセント進んだか
    var progressInDay: Double {
        return progress(inComponents: [.year, .month, .day])
    }

    /// 今月が何パーセント進んだか
    var progressInMonth: Double {
        return progress(inComponents: [.year, .month])
    }

    /// 今年が何パーセント進んだか
    var progressInYear: Double {
        return progress(inComponents: [.year])
    }

    /// 今週が何パーセント進んだか
    var progressInWeek: Double {
        return progress(inComponents: [.year, .month, .weekday, .weekOfYear])
    }

    /// Component を元に経過割合を算出
    private func progress(inComponents components: [Calendar.Component]) -> Double {
        let calendar = Calendar(identifier: .gregorian)
        var start = calendar.dateComponents(Set(components), from: self)

        guard let targetComponent = components.last else { return 0 }

        if targetComponent == .weekOfYear {
            // 開始曜日に合わせて調整(微妙感あるが…)
            start.weekday = 1 // 月曜開始の場合
        }

        guard let startDate = calendar.date(from: start),
            let endDate = calendar.date(byAdding: targetComponent, value: 1, to: startDate) else { return 0 }

        return self.timeIntervalSince(startDate) / endDate.timeIntervalSince(startDate)
    }

}

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?