Swift 3 Easy way to truncate Date to start of the day/month/year

后端 未结 2 2136
挽巷
挽巷 2021-02-19 22:39

Is there any easy way to truncate date like we can do in Oracle Database? For example, I need to set value starting from midnight. In Oracle I can do TRUNC(SYSDATE). But I canno

2条回答
  •  梦谈多话
    2021-02-19 23:11

    Calendar has dedicated methods:

    • Start of the day

        let truncated = Calendar.current.startOfDay(for: Date())
      
    • Start of the month

        let now = Date()
        var startOfMonth = now
        var timeInterval : TimeInterval = 0.0
        Calendar.current.dateInterval(of: .month, start: &startOfMonth, interval: &timeInterval, for: now)
      
        print(startOfMonth)
      
    • Start of the year

        let now = Date()
        var startOfYear = now
        var timeInterval : TimeInterval = 0.0
        Calendar.current.dateInterval(of: .year, start: &startOfYear, interval: &timeInterval, for: now)
      
        print(startOfYear)
      

    Or as Date extension

    extension Date {
        
        func startOf(_ dateComponent : Calendar.Component) -> Date {
            var calendar = Calendar.current
            calendar.timeZone = TimeZone(secondsFromGMT: 0)!
            var startOfComponent = self
            var timeInterval : TimeInterval = 0.0
            calendar.dateInterval(of: dateComponent, start: &startOfComponent, interval: &timeInterval, for: now)
            return startOfComponent
        }
    }
    
    let now = Date()
    
    let startOfDay = now.startOf(.day)
    let startOfMonth = now.startOf(.month)
    let startOfYear = now.startOf(.year)
    

    Regarding the time zone issue you can set the time zone of the current calendar accordingly.

提交回复
热议问题