naoty / Timepiece

Intuitive date handling in Swift
MIT License
2.63k stars 147 forks source link

Add methods to create a Date by truncating the components #82

Closed naoty closed 7 years ago

naoty commented 7 years ago

This PR adds below methods.

let date = Date(year: 2014, month: 8, day: 14, hour: 20, minute: 25, second: 43)
date.truncated([.month, .day]) //=> Date(year: 2014, month: 1, day: 1, hour: 20, minute: 25, second: 43)
date.truncated(from: .hour) //=> Date(year: 2014, month: 8, day: 14, hour: 0, minute: 0, second: 0)

These are useful when you want the beginning of a period. For example, if you want to filter commits in this month, you will be able to write below.

let firstDay = Date().truncated(from: .day)!
let nextFirstDay = (firstDay + 1.month)!
commits.filter { (firstDay ..< nextFirstDay).contains($0.commitDate) }

Feel free to post a reaction or comment.